Javascript 在componentDidMount中监视方法调用
我想测试在React组件的componentDidMount生命周期方法中调用的一些自定义方法Javascript 在componentDidMount中监视方法调用,javascript,reactjs,ecmascript-6,jestjs,enzyme,Javascript,Reactjs,Ecmascript 6,Jestjs,Enzyme,我想测试在React组件的componentDidMount生命周期方法中调用的一些自定义方法 componentDidMount() { getData().then(res => { console.log(res); this.setState({ rate: res.data.bpi.USD.rate_float }); }); } 我正在从api.js导入getData方法: export const
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);
});
});
我做错了什么
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);
});
});
从“…/api”导入{getData};
mock(“…/api”);
描述(“应用程序”,()=>{
描述(“当componentDidMount时调用getData”,()=>{
mockResolvedValue({data:…});
const wrapper=mount(,应该在组件实例化时调用componentDidMount
)
getData
可以通过模拟axios
;以类似的方式进行测试。什么是getData以及它在哪里定义?getData()
-那不是App-method。@estus我是从另一个文件导入它的。如果我是从另一个文件导入它,我该如何测试它?你能在问题中说明这一点吗?代码相关的问题应该包含。然后你不能在App.prototype上监视它。因为它不是一个方法。很可能这应该通过jest.mock
@estus-up来完成注明问题日期。尝试将const-spy
放在const-wrapper
下面。而不是App.prototype
尝试wrapper.instance()
。
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);
});
});