【发布时间】:2019-01-29 16:56:32
【问题描述】:
我想测试一些在 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 › Calls getData when componentDidMount › encountered a declaration exception
并给我以下错误:
TypeError: Cannot read property '_isMockFunction' of undefined
我做错了什么?
【问题讨论】:
-
什么是getData,它在哪里定义?
getData()- 这不是 App 方法。 -
@estus 我正在从另一个文件中导入它。如果我从另一个文件中导入它,我该如何测试它?
-
你能在问题中显示这个吗?与代码相关的问题应包含 stackoverflow.com/help/mcve 。然后你不能在 App.prototype 上窥探它。因为它不是一种方法。这很可能应该通过
jest.mock完成。 -
@estus 更新了问题。
-
尝试将
const spy放在const wrapper下方。而不是App.prototype尝试wrapper.instance()。
标签: javascript reactjs ecmascript-6 jestjs enzyme