reactjs - 开 Jest 如何等待基于模拟事件调用模拟

标签 reactjs enzyme jestjs

我有一个这样的测试失败了,因为没有调用模拟,问题是模拟被调用但在测试完成之前。

test('should submit if proper values', () => {
  const spy = jest.fn().mockReturnValue({
    data: {
      authenticateUser: {
        id: 123,
        token: 'lol'
      }
    }
  });
  mountedWrapper.setProps({
    loginMutation: spy
  });
  expect(spy).not.toHaveBeenCalled();
  email.simulate('change', {
    target: { name: 'username', value: 'email@test.com' }
  });
  password.simulate('change', {
    target: { name: 'password', value: 'secret' }
  });
  form.simulate('submit');
  expect(spy).toHaveBeenCalled();
});

但是,如果我添加以下 setTimeout,我可以让测试通过

  setTimeout(() => {
    expect(spy).toHaveBeenCalled();
  }, 0);

不过,我正在寻找一种更好的方法来解决上述问题。有没有没有 setTimeout 的解决方案?

最佳答案

看起来您正在尝试测试一些异步代码。你读了吗this ?在 callbacks 部分,您可以找到:

By default, Jest tests complete once they reach the end of their execution. That means this test will not work as intended:

// Don't do this!
test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter');
  }

  fetchData(callback);
});

The problem is that the test will complete as soon as fetchData completes, before ever calling the callback. There is an alternate form of test that fixes this. Instead of putting the test in a function with an empty argument, use a single argument called done. Jest will wait until the done callback is called before finishing the test.

test('the data is peanut butter', done => {
  function callback(data) {
    expect(data).toBe('peanut butter');
    done();
  }

  fetchData(callback);
});

If done() is never called, the test will fail, which is what you want to happen.

这是回调的例子,但你也可以使用promises , .resolves/.rejects , 和 async/await .

关于reactjs - 开 Jest 如何等待基于模拟事件调用模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435576/

相关文章:

html - 在 Reaction 创建的网格中对齐文本

javascript - 使用 React router 进行 enzyme 集成测试测试 - 使用链接测试组件更新

javascript - enzyme 模拟提交表单,无法读取未定义的属性 'value'

vue.js - 为什么 $nextTick 中的期望永远不会失败?

ecmascript-6 - Jest 是否支持 ES6 导入/导出?

javascript - 如何使用 Jest 和 React 测试库测试类名

javascript - ownProps 缺少通过 mapStateToProps 添加的 Prop

reactjs - 有没有办法将泛型类型传递给react useReducer hook 中使用的reducer?

reactjs - 关闭应用程序后如何在React Native中实现推送通知

javascript - 你如何测试 enzyme/mocha/chai 中 div 或其他元素的含量?