Jest提供了一种模拟函数的方法,如文档中所述
apiGetMethod = jest.fn().mockImplementation(
new Promise((resolve, reject) => {
const userID = parseInt(url.substr('/users/'.length), 10);
process.nextTick(
() => users[userID] ? resolve(users[userID]) : reject({
error: 'User with ' + userID + ' not found.',
});
);
});
);
但是,当在测试中直接调用函数时,这些函数似乎只能工作 .
describe('example test', () => {
it('uses the mocked function', () => {
apiGetMethod().then(...);
});
});
如果我有一个如此定义的React组件,我该如何模拟它?
import { apiGetMethod } from './api';
class Foo extends React.Component {
state = {
data: []
}
makeRequest = () => {
apiGetMethod().then(result => {
this.setState({data: result});
});
};
componentDidMount() {
this.makeRequest();
}
render() {
return (
<ul>
{ this.state.data.map((data) => <li>{data}</li>) }
</ul>
)
}
}
我不知道如何使它如此 Foo
组件调用我的模拟 apiGetMethod()
实现,以便我可以测试它是否正确呈现数据 .
(这是一个简化的,人为的例子,为了理解如何模拟内部反应组件的函数)
编辑:api.js文件为清楚起见
// api.js
import 'whatwg-fetch';
export function apiGetMethod() {
return fetch(url, {...});
}
3 回答
您必须像这样模拟
./api
模块并导入它,以便您可以设置模拟的实现在您的测试中可以使用mockImplementation设置模拟应该如何工作:
如果来自@Andreas的答案的
jest.mock
方法对你不起作用 . 您可以在测试文件中尝试以下操作 .这应该在你
Foo
组件中执行apiGetMethod
的模拟版本 .模拟这个的另一个解决方案是: