測試應該可以在程式重構時發揮助益,如果在程式重構時一直修改寫好的測試,那麼這可能代表測試到不對的東西。
it('updates text', async () => {
const wrapper = mount(Component)
await wrapper.trigger('click')
expect(wrapper.text()).toContain('updated')
await wrapper.trigger('click')
wrapper.text().toContain('some different text')
})
wrapper.vm.$emit('foo')
wrapper.vm.$emit('foo', 123)
/*
`wrapper.emitted()` 返回以下对象:
{
foo: [[], [123]]
}
*/
判斷 custom evnt 是否如預期
// 断言事件已经被触发
expect(wrapper.emitted().foo).toBeTruthy()
// 断言事件的数量
expect(wrapper.emitted().foo.length).toBe(2)
// 断言事件的有效数据
expect(wrapper.emitted().foo[1]).toEqual([123])
export function setGlobals() {
global.window.localStorage = {
setItem: (key, value) => null,
getItem: (key) => [],
};
}
test('has blah class', () => {
expect(wrapper.contains('.blah')).toBe(true);
});
// check multiple elements by verifying count
test('has blah classes', () => {
expect(wrapper.findAll('.blah').length).toBe(10);
});
** 注意: contain 預計未來會被官方淘汰,使用 find 或是 findComponent 較佳
test('has blah class', () => {
expect(wrapper.find('.blah').exists()).toBe(true);
});
Remember, this test is all about making sure the component behaves correctly given the current state of the store.
為了測試元件行為,我們需要偽造 vuex getter,若沒有 getter 則會噴以下錯誤
[Vue warn]: Error in getter for watcher "selectedLabels": "TypeError: Cannot read property 'getters' of undefined"
在測試中增加 computed 來偽造 vuex getter 就可以正常執行
const wrapper = shallowMount(ClassMenu, {
computed: {
selectedModeClassListType: () => 'select',
selectedLabels: () => [...],
}
});
拿掉煩人的 Deprecation warning
import { config } from '@vue/test-utils';
config.showDeprecationWarnings = false;
修正 [Vue warn]: Unknown custom element
package.json
"jest": {
"setupFiles": [
"./src/specs/setup.js"
]
}