为使用服务的功能组件编写测试。尝试在服务返回错误时测试方案。但是收到错误"mockRejectedValueOnce 不是一个函数"。有人可以帮忙吗?
测试方案,其中数据是从服务传递接收的,因此不会缺少依赖项。
import {render, cleanup, wait} from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect'
import ChatList from './../components/ChatList';
import getMessages from "./../service";
jest.mock("./../service");
describe("ChatList renders chat",()=>{
it("renders error when error occurs during data fetch",()=>{
getMessages.mockRejectedValueOnce('an error');
const {getByTestId, queryByTestId} = render(<ChatList/>);
expect(getMessages).toHaveBeenCalledTimes(1);
wait(() => {
expect(queryByTestId("messages-list")).toBeNull();
expect(getByTestId("error-wrapper")).toBeInTheDocument();
});
});
});
消息服务如下所示:
export default function getMessages() {
return new Promise(function(resolve, reject) {
//array of messgaes
});
};
实际结果:
TypeError: _service2.default.mockRejectedValueOnce is not a function
at Object.it (src/_tests_/ChatList.test.js:48:80)
at process._tickCallback (internal/process/next_tick.js:68:7)
我通过将上面的代码 mockRejectedValueOnce 更改为 mockImplementation来解决上面的问题:
getMessages.mockImplementation(() => Promise.reject("error"));