使用Jest模拟Axios并模拟Windows.Location.Assignment

问题描述 投票:1回答:1

一些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 mock中触发“then”时,模拟的window.location.assign方法每次都会失败。

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

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

reactjs axios-mock-adapter jest-mock-axios
1个回答
0
投票

不确定你是否正确地模仿了window对象。但你总是可以在你的jest测试文件中模拟它,如下所示:

it('test', () => {
  window.location.assign = jest.fn();
  // your function that you want to test
  expect(window.location.assign).toBeCalledWith('/nextscreen');
});
© www.soinside.com 2019 - 2024. All rights reserved.