【问题标题】:What is the advantage of using beforeEach function in Jest在 Jest 中使用 beforeEach 函数有什么好处
【发布时间】: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


【解决方案1】:

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

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

大多数情况下,第二种方法更受青睐,因为没有共享状态的独立测试是一种很好的做法。

【讨论】:

【解决方案2】:

如前所述,beforeEach 在每次测试之前被调用

使用beforeAllbeforeEach 的另一个重要优点是您可以将返回Promiseasync 函数的函数传递给它们,Jest 将等待生成的Promise在继续之前解决。

所以beforeAllbeforeEach 必须用于任何异步设置工作:

describe('something', () => {

  let setInBeforeAll, setinBeforeEach;

  beforeAll(() => {
    return returnsAPromise().then(val => {  // <= you can return a Promise...
      setInBeforeAll = val;
    });
  });

  beforeEach(async () => {  // ...or use an async function
    setInBeforeEach = await alsoReturnsAPromise();
  });

  it('should do something', () => {
    // both setInBeforeAll and setInBeforeEach are available here
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-12
    • 2014-03-14
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多