【发布时间】:2017-04-19 15:37:00
【问题描述】:
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, {...});
}
【问题讨论】:
-
apiGetMethod是如何注入到你的模块中的? -
import { apiGetMethod } from './api';在Foo组件文件的顶部
标签: unit-testing reactjs mocking jestjs