【问题标题】:Using Jest to Mock Axios and Mock Windows.Location.Assignment使用 Jest 模拟 Axios 和模拟 Windows.Location.Assignment
【发布时间】:2023-04-02 09:26:01
【问题描述】:

一些 ReactJs 组件正在使用 Axios NPM 库来触发 Http Posts。使用 Axios 的帖子示例,我们有:

axios.post('/user', {
       firstName: 'Fred',
       lastName: 'Flintstone'
   })
   .then(function (response) {
       window.location.assign('/nextscreen');
   })
  .catch(function (error) {
    console.log(error);
  }); 

发布后,触发“then”以移至下一页。

我们正在使用 Jest 和 Enzyme 对 Axios 功能进行单元测试。此外,我们已经成功地孤立地模拟了: - 使用 jest-mock-axios 发布 Axios - 使用 jest mock 的 window.location.assign 方法。

但是,当在 Axios 模拟中触发“then”时,模拟的 window.location.assign 方法每次都会失败。

是否可以同时模拟 Axios 调用和 window.location.assign ?

我可以传入一个包装 window.location.assign 方法的方法,但这是不正确的。

【问题讨论】:

  • 你是如何模拟你的 axios 和 window.location.assign 的?

标签: reactjs axios-mock-adapter jest-mock-axios


【解决方案1】:

不确定您是否正确地模拟了 window 对象。 但是你总是可以像这样在你的 jest 测试文件中模拟它:

it('test', () => {
  window.location.assign = jest.fn();
  // your function that you want to test
  expect(window.location.assign).toBeCalledWith('/nextscreen');
});

【讨论】:

    猜你喜欢
    • 2022-07-21
    • 1970-01-01
    • 2020-01-04
    • 2019-07-22
    • 2018-12-18
    • 2020-11-06
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多