我正在为一个组件编写单元测试。我的组件有一个使用 axios 的方法。我想为它编写单元测试。这是我的写法,但出现错误。
import axios from "axios";
jest.mock('axios');
jest.mock('axios', () => ({ get: jest.fn(),post: jest.fn(), create: jest.fn() }));
test("on search it should call get store", () => {
axios.get.mockImplementationOnce(() => Promise.resolve(data));
const wrapper = shallow(<ComponentA />);
const spy = jest.spyOn(wrapper.instance(), "getStores");
wrapper.setState({
searchText: "test1"
});
wrapper.instance().onSearchClick();
expect(spy).toHaveBeenCalledWith("test1");
});
Run Code Online (Sandbox Code Playgroud)
这是方法
getStores = term => {
const uri = URI("")
.path("/api/link")
.addQuery({term: term})
.toString();
return axios.get(uri)
.then(response => {
const storeResponse = response.data;
return storeResponse;
} catch (error) {}
this.props.onStoreFetch(stores, false);
} …Run Code Online (Sandbox Code Playgroud)