6

我需要通过模拟 react-aad-msal 为下面的类编写单元测试用例。我怎么能嘲笑它?我读过那个酶模拟组件,但我得到错误

console.error node_modules/react-aad-msal/dist/commonjs/Logger.js:69
      [ERROR] ClientAuthError: User login is required.

我认为这与单元测试无关

    import React, { Component } from "react";
    import "./App.css";
    import { authProvider } from "./authProvider";
    import { AzureAD, AuthenticationState, IAzureADFunctionProps } from "react-aad-msal";
    import Home from "./pages/Home";
    import { ThemeProvider } from "styled-components";
    import { lightTheme } from "./themes";

    export default class App extends Component<{}, { theme: any }> {
      static displayName = App.name;
      constructor(props: any) {
        super(props);

        this.state = {
          theme: lightTheme
        };
      }

      render() {
        return (
          <AzureAD provider={authProvider} forceLogin>
            {({ authenticationState, accountInfo, error }: IAzureADFunctionProps) => {
              switch (authenticationState) {
                case AuthenticationState.Authenticated:
                  return (
                    <ThemeProvider theme={this.state.theme}>
                      <Home userInfo={accountInfo!=null? accountInfo.account.name: ""} />
                    </ThemeProvider>
                  );
                case AuthenticationState.Unauthenticated:
                  return (
                    <div>
                      {
                        <p>
                          <span>
                            An error {error} occured during authentication, please try
                            again!
                          </span>
                        </p>
                      }
                      <p>
                        <span>Hey stranger, you look new!</span>
                      </p>
                    </div>
                  );
                case AuthenticationState.InProgress:
                  return <p>Authenticating...</p>;
              }
            }}
          </AzureAD>
        );
      }
    }
4

1 回答 1

0

Using jest I've been able to mock calls to an authProvider defined as such :

export const authProvider = new MsalAuthProvider(config, authenticationParameters, options);

My component need to get an access token so I mock the call to getAccessToken from the authProvider

So in my tests :

import {authProvider} from "../../app/AuthProvider";
import {render} from "@testing-library/react";

jest.mock('../../app/AuthProvider');

describe('Component', () => {
  it('should match snapshot', () => {
    authProvider.getAccessToken.mockResolvedValue({
      accessToken: 'accessToken'
    });

    const {container} = render(Component);

    expect(container.firstChild).toMatchSnapshot("Component");
  });
});

于 2020-05-19T08:29:00.107 回答