我正在为React SPA运行Jest测试套件。我正在尝试为登录页面编写测试。如果登录尝试的结果是404,我应该调用许多函数,但是我不知道为什么没有调用它们。
我正在尝试模拟对用户进行身份验证的访存调用,并确保随后调用正确的函数。下面的代码试图做的是:
import { render, fireEvent } from "@testing-library/react";
import React from "react";
import SignIn from "./signIn";
import 'jest-dom/extend-expect';
import 'isomorphic-fetch';
const mockResponse = (status: number, response: BodyInit) => {
const fetchResponse: Response = new Response(response, {status:status});
return fetchResponse;
}
describe("<SignIn>", () => {
it("sets basic creds, auth header, usingIMS, and authenticated when it gets a 404", async () => {
const setBasicCreds = jest.fn();
const setAuthHeader = jest.fn();
const setUsingIms = jest.fn();
const setAuthenticated = jest.fn();
const baseUrl = 'https://testUrl';
const fakePromise = Promise.resolve(mockResponse(404, JSON.stringify({message: "test"})));
window.fetch = jest.fn().mockImplementationOnce(() => {
return fakePromise;
});
const { getByTestId } = render(<SignIn baseUrl={baseUrl} setBasicCreds={setBasicCreds} setAuthenticated={setAuthenticated}
setAuthHeader={setAuthHeader} setUsingIms={setUsingIms} connectionName={signInProps.connectionName}></SignIn>);
const username: HTMLElement = getByTestId("signInUsername");
fireEvent.change(username, {
target: { value: 'username' },
});
const password: HTMLElement = getByTestId("signInPassword");
fireEvent.change(password, {
target: { value: 'password' },
});
const submitButton: HTMLElement = getByTestId("signInSubmitButton");
fireEvent.click(submitButton);
await Promise.all([fakePromise]);
expect(setBasicCreds).toHaveBeenCalled();
expect(setAuthHeader).toHaveBeenCalled();
expect(setUsingIms).toHaveBeenCalledWith(false);
expect(setAuthenticated).toHaveBeenCalledWith('Authenticated');
});
});
运行测试套件时,它在第一个expect
上失败,表示从未调用setBasicCreds
。我想念什么?
答案 0 :(得分:0)
在很久以后跟进我的问题,答案是使用集成测试。与Jest单元测试相比,使用Cypress这样的框架进行集成测试更有意义。