【发布时间】:2021-05-13 06:59:22
【问题描述】:
/api
index.js
base.js
notebooks.js
/components
AllNotebooks/
NewNotebook/
/containers
AllNotebooks/
NewNotebook/
common/withList/
我正在使用jest.spyOn.mockImplementation 模拟我的notebooks.js api,这是<NewNotebookContainer /> 的工作测试用例,但它没有被AllNotebooksContainer 模拟。
// api/base.js
const instance = axios.createinstance({url: BASE_URL})
export default instance
// api/notebooks.js
const getAll = () => instance.get("/notebooks");
const create = id => instance.post("/notebooks")
export {getAll, create}
// api/index.js
import * as notebooksApi from './notebooks'
export {notebooksApi}
现在,它适用于
import NewNotebook from "../../components/NewNotebook";
import { notebooksApi } from "../../api/index";
const NewNotebookContainer = function () {
const handleSubmit = () => {
if (!newNotebook.title.length) {
return false;
} else {
return notebooksApi.create(newNotebook).then(() => {
toggleModal();
});
}
};
return (
<NewNotebook handleSubmit={handleSubmit}/>
);
};
export default NewNotebookContainer;
// ./__test__/index.js
it("should invoke api if title exists", async () => {
renderNotebook();
const spy = jest
.spyOn(notebooksApi, "create")
.mockImplementation((x) => Promise.resolve(x));
await act(() => {
fireEvent.click(screen.getByRole("button", { name: /Create Notebook/ }));
return Promise.resolve();
});
expect(spy).toHaveBeenCalledTimes(1);
});
但是,notebookApi 不会被 <AllNotebooksContainer /> 嘲笑
// AllNotebooksContainer/index.js
import AllNotebooks from "../../components/AllNotebooks";
import { notebooksApi } from "../../api/index";
import withList from "../common/withList";
const AllNotebooksContainer = withList(AllNotebooks, notebooksApi.getAll);
export default AllNotebooksContainer;
// ../withList/index.js
const withList = (Component, getList) => {
return function WithList(props)
useEffect(async () => {
// invoke getList and store data in state
}, []);
if (!loading) {
return <Component data={list} {...props} />;
} else {
return <Loading />;
}
};
};
// ./__test__/index.js
it("should render correct number of <Notebook />", async () => {
const spy = jest
.spyOn(notebooksApi, "getAll")
.mockImplementation(() => Promise.resolve({ data: mockData }));
renderComponent();
await waitFor(() => expect(spy).toHaveBeenCalledTimes(1));
// some assertions
});
对于<AllNotebooksContainer />,实际方法getAll 正在被调用,我在终端中得到Network Error,并且expect(spy).toHaveBeenCalledTimes(1) 失败,并以0 作为接收值。
【问题讨论】:
标签: reactjs jestjs react-testing-library