Jest——模拟一个在 React 组件内部调用的函数 [英] Jest -- Mock a function called inside a React Component
问题描述
Jest 提供了一种模拟函数的方法,如其文档中所述
Jest provides a way to mock functions as described in their docs
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.',
});
);
});
);
然而,这些模拟似乎只有在测试中直接调用函数时才有效.
However these mocks only seem to work when the function is called directly in a test.
describe('example test', () => {
it('uses the mocked function', () => {
apiGetMethod().then(...);
});
});
如果我有一个这样定义的 React 组件,我该如何模拟它?
If I have a React Component defined as such how can I mock it?
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()
实现,以便我可以测试它是否正确地使用数据呈现.
I have no idea how to make it so Foo
component calls my mocked apiGetMethod()
implementation so that I can test that it renders properly with data.
(这是一个简化的、人为的例子,用于理解如何模拟在 React 组件内部调用的函数)
(this is a simplified, contrived example for the sake of understanding how to mock functions called inside react components)
api.js 文件以供清晰
edit: api.js file for clarity
// api.js
import 'whatwg-fetch';
export function apiGetMethod() {
return fetch(url, {...});
}
推荐答案
你必须像这样模拟 ./api
模块并导入它,以便你可以设置模拟的实现
You have to mock the ./api
module like this and import it so you can set the implemenation of the mock
import { apiGetMethod } from './api'
jest.mock('./api', () => ({ apiGetMethod: jest.fn() }))
在您的测试中可以使用 mockImplementation 设置模拟应该如何工作:
in your test can set how the mock should work using mockImplementation:
apiGetMethod.mockImplementation(() => Promise.resolve('test1234'))
这篇关于Jest——模拟一个在 React 组件内部调用的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!