玩笑提供一種方式來嘲笑作爲其文檔描述玩笑 - 莫克一個叫做陣營內部組件功能
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'注入到模塊中? –
'從'./api'導入{apiGetMethod};'在'Foo'組件文件的頂部 –