开玩笑-模拟一个在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 Component,该如何模拟呢?
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来设置模拟的工作方式:
apiGetMethod.mockImplementation(() => Promise.resolve('test1234'))
这篇关于开玩笑-模拟一个在React组件内部调用的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!