我需要通过模拟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>
);
}
}发布于 2020-05-19 16:29:00
使用jest,我已经能够模拟对如下定义的authProvider的调用:
export const authProvider = new MsalAuthProvider(config, authenticationParameters, options);我的组件需要获得一个访问令牌,所以我模拟了从authProvider到getAccessToken的调用
所以在我的测试中:
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");
});
});https://stackoverflow.com/questions/60275938
复制相似问题