在Jest中使用beforeEach函数的好处是什么 [英] What is the advantage of using beforeEach function in Jest

查看:286
本文介绍了在Jest中使用beforeEach函数的好处是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过手册来学习开玩笑. .在Jest中使用beforeEach函数有什么优势?

I am learning Jest with this manual. What is the advantage of using beforeEach function in Jest?

我想检测动作调度.我认为以下两个代码将具有相同的行为.

I want to detect action dispatching. I think two of the following codes will have the same behaviour.

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()
  })
})

推荐答案

没有这些示例没有相同的行为.您可以在Jest的文档中找到( https://jestjs.io/docs/zh/setup-teardown ).beforeEach方法在每种测试方法之前执行.

No these example do not have the same behaviour. As you can find in the documentation of Jest (https://jestjs.io/docs/en/setup-teardown) the beforeEach method is executed before each test method.

因此,在第一个示例中,您只需创建一次actionstore,并且在第二种测试期间仍然可以使用在第一种测试方法(increment)中所做的更改.在第二个示例中,为每个测试重新创建actionstore.因此,在第一种测试方法中所做的更改在第二种测试方法中不可用.

So in your first example, you only create the action and store once, and the changes made in the first test method (increment) are still available during the second test. In your second example, the action and store are recreated for each test. So the changes made in the first test method are not available in the second test method.

在大多数情况下,首选第二种方法,因为没有共享状态的独立测试是一种好习惯.

Most of the time the second approach is prefered because of independent tests with no shared state is a good practice.

这篇关于在Jest中使用beforeEach函数的好处是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆