component test 問題集(Vue2 + TS + Jest + vue-test-utils)


Posted by TempuraEngineer on 2022-03-19

1. 無法透過wrapper.vm調用methods


myComponent & { [key: string]: any }對應line78的第1個type parameter。第1個參數因為有extend Vue,所以它必須是一個vue instance,否則會出type error

至於為什麼還要加{ [key: string]: any },因為這樣能讓型別變寬鬆(relaxed type),它就是把vm定義成一個包了不知道有甚麼屬性的物件

如此一來vm調用vm下面的屬性、方法就不會再出"property ... does not exist on type Vue"

import { shallowMount, createLocalVue, Wrapper } from '@vue/test-utils';
import myComponent from '@/components/myComponent.vue';

const localVue = createLocalVue();

const wrapper: Wrapper<myComponent & { [key: string]: any }> = shallowMount(myComponent, {
    localVue,
})

describe('', () => {
    beforeEach(() => {
        wrapper.vm.getData();
    })

    it('', () => {
        // write your code here
    })
})
(Method isn't available in unit test)[https://stackoverflow.com/questions/57021241/method-isnt-available-in-unit-test]
(vue-test-utils/ How to use typescript correctly?)[https://github.com/vuejs/vue-test-utils/issues/255]


2. localStorage is not defined

這不太正常,先檢查版本。

從v20開始可以自己在jest.config.js設定testEnvironment

Custom Environment: It is now possible to add a @jest-environment node|jsdom annotation to the doc-block comment of a test file to use a test environment different from the default for individual tests.

v24.9開始Jest有testEnvironment預設值為jsdom,所以跑browser code時就算在Node環境下還是可以呼叫到window底下的東西

(2022/5/26更新)
2022/4/25 v28發布,不再自動幫你安裝jest-environment-jsdom,但jest-environment-jsdom還是有繼續維護,有需要可以自行安裝

Jest 28 will remove jest-jasmine2 and jest-environment-jsdom from the default distribution of Jest. The packages will still be actively maintained as part of the Jest project and be published separately. Users will need to install these packages to use them.

Please note that both of the removed modules (jest-environment-jsdom and jest-jasmine2) are still actively maintained and tested in the same way, so the only breaking change here is that you'll need to explicitly install them.

如果不幸就只能用v20以下的版本,也可以自己mock localStorage

實戰Jest配置
Testing with Node, Jest, and JSDOM
How do I deal with localStorage in jest tests?
Jest 28
testEnvironmentOptions


3. async function還沒結束測試就跑完

使用$nextTick確保async function結束再跑測試

Asynchronous behavior outside of Vue


4. 明明就有測試檔,為什麼Jest說沒有


因為路徑不符合。預設路徑是tests/unit。如果有改過資料夾結構要去jest.config.js或package.json的jest位置改testMatch


#Jest #vue-test-utils #component test







Related Posts

[css] 網頁字型渲染的優化

[css] 網頁字型渲染的優化

【單元測試的藝術】Chap 10: 遺留程式碼

【單元測試的藝術】Chap 10: 遺留程式碼

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段四:個人專案~重構)

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段四:個人專案~重構)


Comments