【发布时间】:2019-08-23 15:31:51
【问题描述】:
我正在用这个manual 学习 Jest。在 Jest 中使用beforeEach 函数有什么好处?
我想检测动作调度。我认为以下两个代码将具有相同的行为。
describe('dispatch actions', () => {
const localVue = createLocalVue()
localVue.use(Vuex)
let actions = { increment: jest.fn(), decrement: jest.fn() }
let store = new Vuex.Store({ state: {}, actions })
const wrapper = shallowMount(Counter, { store, localVue })
it('dispatches "increment" when plus button is pressed', () => {
wrapper.find('button#plus-btn').trigger('click')
expect(actions.increment).toHaveBeenCalled()
})
it('dispatches "decrement" when minus button is pressed', () => {
wrapper.find('button#minus-btn').trigger('click')
expect(actions.decrement).toHaveBeenCalled()
})
})
describe('dispatch actions', () => {
const localVue = createLocalVue()
localVue.use(Vuex)
let actions
let store
beforeEach(() => {
actions = {
increment: jest.fn(),
decrement: jest.fn()
}
store = new Vuex.Store({
state: {},
actions
})
})
it('dispatches "increment" when plus button is pressed', () => {
const wrapper = shallowMount(Counter, { store, localVue })
wrapper.find('button#plus-btn').trigger('click')
expect(actions.increment).toHaveBeenCalled()
})
it('dispatches "decrement" when minus button is pressed', () => {
const wrapper = shallowMount(Counter, { store, localVue })
wrapper.find('button#minus-btn').trigger('click')
expect(actions.decrement).toHaveBeenCalled()
})
})
【问题讨论】:
-
除非您需要在每次测试之前重置商店的状态,否则不需要。但是如果在测试过程中你更新了 store,并且测试在某种程度上依赖于 store 的状态,那么最好在每次测试之前重置,否则测试的顺序会很重要
标签: javascript vue.js jestjs