具有开玩笑和酶的模拟功能模块

时间:2018-04-10 12:41:19

标签: reactjs mocking jestjs enzyme

我有一个React组件,它从另一个模块调用一个方法 该模块只返回1个方法:

export default (url, method, authorization, body) => {
  const headers = { 'Content-Type': 'application/json' }
  if (authorization) headers.Authorization = localStorage.getItem('id_token');
  return fetch(url, {
    method,
    headers,
    body: JSON.stringify(body)
  }).then(res => res.json());
}

我想模拟这个方法/模块,因此在使用它测试组件时不会调用真实代码。
我是React / Jest / Enzyme的新手所以我可能会错过一些简单的东西。

在我的测试文件中:

jest.mock('../../utils/fetch.js', () => () => {
  Promise.resolve({_id: 1});
});
import fetch from '../../utils/fetch';

使用方法的地方:

return fetch('/api/items', 'post', true, newItem).then(res => {
  this.props.history.push(`/items/${res._id}`);
}).catch(console.log);

1 个答案:

答案 0 :(得分:1)

所以你有一个模块返回一个将返回一个promise的函数。如果您只想测试快乐路径,只需从模拟中返回已解决的承诺:

jest.mock('./my-function.js', () => () => Promise.resolve('foo'));

如果您需要在测试期间设置函数的结果,请使用间谍模拟模块,并在测试中稍后设置结果:

jest.mock('./my-function.js', () => jest.fn());
import myFunction from './my-function.js'
describe('foo',()=>{
  it('the happy pass',()=> {
     myFunction.mockImplementation(() => Promise.resolve('foo'))
    //your assertion here 
  })

  it('when it fails',()=> {
     myFunction.mockImplementation(() => Promise.reject())
     //your assertion here 
  })
})
})

请注意,您必须在模块顶部模拟它。否则你将导入原始文件,稍后用模拟替换模块,这对导入的模块没有影响。把嘲笑想象成一种说出如何解决导入的方式。因此在导入之后嘲笑某些东西将没有任何效果。

相关问题