反应:如何模拟Auth0以进行Jest测试

问题描述 投票:0回答:1

我正在使用React(react-create-app和TypeScript)。使用Auth0登录。

我想用Jest编写测试,并且我发现了这个资源,基本上这是唯一有关模拟Auth0对象的事情。

所以我的代码如下:

import React from "react";
import ReactDOM from "react-dom";
import TopBar from "./index";
import {
  useAuth0
} from "react-auth0-spa";

const user = {
  email: "[email protected]",
  email_verified: true,
  sub: "google-oauth2|12345678901234"
};

// intercept the useAuth0 function and mock it
jest.mock("react-auth0-spa");

describe("First test", () => {
  beforeEach(() => {
    // Mock the Auth0 hook and make it return a logged in state
    useAuth0.mockReturnValue({
      isAuthenticated: true,
      user,
      logout: jest.fn(),
      loginWithRedirect: jest.fn()
    });
  });

  it("renders without crashing", () => {
    const div = document.createElement("div");
    ReactDOM.render( < TopBar / > , div);
  });
});

但是我最终被这个错误所困扰:

Property 'mockReturnValue' does not exist on type '() => IAuth0Context | undefined'.ts(2339)

我在这里迷失了一点,任何帮助将不胜感激!

javascript reactjs typescript auth0 jest
1个回答
0
投票

这是TypeScript错误。您将需要键入模拟的useAuth0,因为原始类型没有名为mockReturnValue的方法。这样的事情应该起作用:

const mockedUseAuth0 = <jest.Mock<typeof useAuth0>>useAuth0;

mockedUseAuth0.mockReturnValue({
  isAuthenticated: true,
  user,
  logout: jest.fn(),
  loginWithRedirect: jest.fn()
});
© www.soinside.com 2019 - 2024. All rights reserved.