我正在尝试模拟 import { Auth0Provider } from "@auth0/auth0-react";
在 React 应用程序中并继续遇到此错误的问题 [Error:出于安全原因,window.crypto 需要运行 auth0-spa-js。]
据我所知,此错误来自 Auth0Client
,它从 import { Auth0Client } from '@auth0/auth0-spa-js';
我的想法是模拟作用域模块 @auth0/auth0-spa-js
并做这样的事情
const handleRedirectCallback = jest.fn(() => ({ appState: {} }));
const buildLogoutUrl = jest.fn();
const buildAuthorizeUrl = jest.fn();
const checkSession = jest.fn();
const getTokenSilently = jest.fn();
const getTokenWithPopup = jest.fn();
const getUser = jest.fn();
const getIdTokenClaims = jest.fn();
const isAuthenticated = jest.fn(() => false);
const loginWithPopup = jest.fn();
const loginWithRedirect = jest.fn();
const logout = jest.fn();
export const Auth0Client = jest.fn(() => {
return {
buildAuthorizeUrl,
buildLogoutUrl,
checkSession,
handleRedirectCallback,
getTokenSilently,
getTokenWithPopup,
getUser,
getIdTokenClaims,
isAuthenticated,
loginWithPopup,
loginWithRedirect,
logout,
};
});
如果我将 Auth0Client
导入到我的任何测试中,这似乎有效,但问题是 Auth0Provider
仍在导入非模拟客户端。有没有办法让 Auth0Provider
导入模拟的 Auth0Client
而不是实际的实现?使用 Auth0Provider
的文件如下所示
// test-utils.js
import React from 'react'
import { render as rtlRender } from '@testing-library/react'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { MockedProvider } from '@apollo/client/testing';
import { Auth0Provider } from "@auth0/auth0-react";
import { Auth0Client } from '@auth0/auth0-spa-js';
// Import your own reducer
import applicationsReducer from "../app/slices/applications.slice";
import { UserProvider } from "../user-context";
import {getUserMock} from "../__tests__/apollo_mocks/get_user.mock"
// const MockedAuth0Provider = jest.requireActual("@auth0/auth0-react").Auth0Provider
function render(
ui,
{
initialState,
mocks,
store = createStore(applicationsReducer, initialState),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return <Auth0Provider clientId="__test_client_id__" domain="__test_domain__">
<Provider store={store}>
<MockedProvider mocks={[getUserMock, ...mocks]} addTypename={false}>
<UserProvider>{children}</UserProvider>
</MockedProvider>
</Provider>
</Auth0Provider>
}
return rtlRender(ui, { wrapper: Wrapper, ...renderOptions })
}
// re-export everything
export * from '@testing-library/react'
// override render method
export { render }
最佳答案
希望这对其他人有帮助,但我最终 mock 了提供者以及我以这种方式使用的其他一些 auth0 模块
jest.mock('@auth0/auth0-react', () => ({
Auth0Provider: ({ children }) => children,
withAuthenticationRequired: ((component, _) => component),
useAuth0: () => {
return {
isLoading: false,
user: { sub: "foobar" },
isAuthenticated: true,
loginWithRedirect: jest.fn()
}
}
}));
这些都在我的setupTests.js
文件中
https://stackoverflow.com/questions/67509953/