玩笑——模拟在 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.
(这是一个简化的、人为的示例,以便理解如何模拟在反应组件中调用的函数)
(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'))
这篇关于玩笑——模拟在 React 组件中调用的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!