Since JSTF (our frontend policy team) adds SonarQube for all FE projects recently. We have to get started with unit test for better code coverage in all projects. Any PR doesn't reach a goal of 60% coverage can't be merged.
To reduce the pain and writing unit test in an efficient way, here are some common cases for jest
and vue-test-util
。
Q: How to mock window?
A:
Q: If there are multiple test cases in a simular pattern, how do you test all of them?
A:
Q: How to end up all promises in jest?
A:
Q: How to mock third party ES Module?
A:
Q: How to mock router?
A:
Q: How to mock route?
A:
Q: How to mock next function in beforeRouteLeave?
A: Use a jest.fn
to trigger call for wrapper.vm
.
Q: How to get/set data in wrapper?
A:
Q: How to mock vue-i18n
?
A: Add a locale object if you access the i18n object directly, and add $t
for mocks for component to render i18n keys.
Q: How to interfere with component methods?
A: Use spyOn
for specific instance methods before shallowMount
.
Q: How to test a dialog called by plugin method?
A: Because it's general to see that a dialog called by plugin method is a Vue instance seperated with our App instance, to access the instance, there is a hacky method. Take bootstrap-vue as example, we should realize what DOM structure the dialog is by reading the third party repo source code, get __vue__
property in the dialog DOM, and then use createWrapper
method to generate a new wrapper。
Work
JavaScript
Jest
Vue
Vue2
Unit Test