LoginSignup
2
1

More than 5 years have passed since last update.

Mocha+Chai+SinonでPromiseの単体テストをするときはPromiseを返そう

Posted at

結論

タイトルのとおりです。

背景

doneを使っていたら、Unhandled promise rejectionではまったのでその解消のため。

本文

Vueでのajax通信にはaxiosを使っています。
例えばajax通信でアイテムの情報を取得するitemsコンポーネントを考えます。

items.vue
import axios from 'axios';
export default {
    data() {
        return {
            items: []
        };
    },
    methods: {
        fetchItems(){
            axios.get('/api/items').then((res) => {
                this.items = res.data;
            });
        },
    },
}

単体テストはMocha+Chai+Sinon+vue-test-utilsで書いてます。
以前までは以下のように書いていました。

item.spec.js
import axios from 'axios';
import { shallow } from 'vue-test-utils';
import items from '@/items';

describe('items component', () => {
    it('fetchItemsでアイテム一覧が取得できる', (done) => {
        const items = [
            { id: 'Test' },
        ];

        const resolved = Promise.resolve({
            data: items,
        });

        sinon.stub(axios, 'get').withArgs('/api/items').returns(resolved);
        const wrapper = shallow(items);
        resolved.then(() => {
            expect(wrapper.vm.items).to.deep.equal(items);
            axios.get.restore();
            done();
        });
    });
});

しかし、このやり方だとresoleved.thenの内部でエラーが発生したとき(例えばexceptが失敗したとき)にUnhandled promise rejectionが発生し、エラーが起きているのはわかってもその詳細がログに表示されませんでした。
doneを使った書き方は古いもののようで、以下のようにreturnでpromiseを戻すようにしたら内部で発生したエラーも表示されるようになりました。

item.spec.js
        return resolved.then(() => {
            expect(wrapper.vm.items).to.deep.equal(items);
            axios.get.restore();
        });

doneは消しておかないと、単体テスト実行時に怒られます。

参考

axiosを利用したVue componentのUnitTest
MochaがPromisesのテストをサポートしました

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1