【问题标题】:Testing function calls in Jest after button click (mocking fetch calls)单击按钮后在 Jest 中测试函数调用(模拟 fetch 调用)
【发布时间】:2019-12-22 04:40:07
【问题描述】:

我正在为 React SPA 运行 Jest 测试套件。我正在尝试为登录页面编写测试。如果登录尝试的结果是 404,我有许多应该调用的函数,但我不知道为什么没有调用它们。

我正在尝试模拟对用户进行身份验证的 fetch 调用,并确保之后调用正确的函数。下面的代码试图做的是:

  • 创建一个虚假的已解决承诺
  • 设置模拟提取以返回已解决的承诺
  • 触发事件以模仿用户的行为(输入用户名/密码,点击“登录”)
  • 等待所有承诺得到解决
  • 检查我的函数是否已被调用
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。我错过了什么?

【问题讨论】:

    标签: reactjs jestjs fetch react-testing-library


    【解决方案1】:

    稍后跟进我的问题,答案是使用集成测试。对于使用像 Cypress 这样的框架的集成测试,我尝试做的事情比 Jest 单元测试更有意义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-30
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多