我想测试一些在 React 组件的 componentDidMount 生命周期方法中调用的自定义方法。
componentDidMount() {
getData().then(res => {
console.log(res);
this.setState({
rate: res.data.bpi.USD.rate_float
});
});
}
我正在从 api.js 导入 getData 方法:
export const getData = () => {
return axios
.get("https://api.coindesk.com/v1/bpi/currentprice.json")
.then(res => {
return res;
});
};
像这样用 Jest 和 Enyzme 测试它:
describe("App", () => {
describe("Calls getData when componentDidMount", () => {
const spy = jest.spyOn(App.prototype, "getData");
const wrapper = mount(<App {...props} />);
wrapper.instance().getData();
expect(spy).toHaveBeenCalled(1);
});
});
失败:App › 在 componentDidMount 时调用 getData › 遇到声明异常
并给我以下错误:
TypeError: Cannot read property '_isMockFunction' of undefined
我做错了什么?
最佳答案
getData
不是 App
方法,它不能在 App
类上被窥探,它在 wrapper.instance( )
组件实例。
可以使用 jest.mock
模拟模块。正确的单元测试需要模拟除测试单元之外的所有内容。 axios
请求可以被模拟为:
import { getData } from '.../api';
jest.mock('.../api');
describe("App", () => {
describe("Calls getData when componentDidMount", () => {
getData.mockResolvedValue({ data: ... });
const wrapper = mount(<App {...props} />);
expect(getData).toHaveBeenCalled(1);
});
});
注意 shallow
enables lifecycle hooks by default ,预计在组件实例化时调用 componentDidMount
。
getData
可以通过模拟 axios
以类似的方式进行测试; this is shown in the manual .
关于javascript - 监视 componentDidMount 中的方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51983644/