■ はじめに
https://dk521123.hatenablog.com/entry/2021/01/07/230317
https://dk521123.hatenablog.com/entry/2021/01/27/225148
の続き。 今回は、flush-promises っていうものを知ったので、メモ。
公式サイト
https://vue-test-utils.vuejs.org/ja/guides/testing-async-components.html
より、重要な部分を一部抜粋 ~~~~~ ■ 非同期動作のテスト コールバックや Promise のようなコンポーネントの非同期動作をテストする場合、 いくつかのテクニックを知っておく必要があります。 1 つの解決策は async function と npm パッケージの flush-promises を使用することです。 ~~~~~
目次
【1】flush-promises 【2】環境設定 【3】サンプル
【1】flush-promises
* 非同期動作に関する単体テストの便利プラグイン
公式サイト
https://www.npmjs.com/package/flush-promises
【2】環境設定
npm add -D flush-promises
【3】サンプル
import { shallowMount } from '@vue/test-utils'; import HelloWorld from '@/components/HelloWorld.vue'; import flushPromises from 'flush-promises'; describe('HelloWorld.vue', () => { it('This is just a sample test', async () => { const wrapper = shallowMount(HelloWorld); const fetchResults = jest.fn().mockResolvedValue({data: 'Hello world!!'}); wrapper.setMethods({fetchResults}); wrapper.find('button').trigger('click'); // flush-promises は堰き止められている // resolve された Promise ハンドラを流します。 // 堰き止められている Promise を流すこととテストの可読性を改善するために // await を flushPromises の呼び出しの前に置きます。 await flushPromises(); expect((wrapper.vm as any).value).toEqual('Hello world!!'); expect(fetchResults.call.length).toEqual(1); }); });
参考文献
https://til.toshimaru.net/2020-07-24
https://qiita.com/iwata@github/items/263accda14620aaed513
関連記事
Jestを使った Vue / TypeScript の単体試験 ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2021/01/07/230317
Jestを使った Vue / TypeScript の単体試験 ~ 基本編 ~
https://dk521123.hatenablog.com/entry/2021/01/27/225148
非同期処理 ~ async/await, Promise ~
https://dk521123.hatenablog.com/entry/2021/03/23/231011
Jestを使った Vue / TypeScript の単体試験 ~ axios 編 ~
https://dk521123.hatenablog.com/entry/2021/01/16/202822
axios ~ 外部API通信ライブラリ ~
https://dk521123.hatenablog.com/entry/2021/01/14/101645
JS単体試験ツール Jest ~ Mock編 ~
https://dk521123.hatenablog.com/entry/2021/01/26/215558