kca*_*rra 2 reactjs jestjs auth0
我正在尝试在反应应用程序中模拟出来import { Auth0Provider } from "@auth0/auth0-react";,并不断遇到此错误的问题[Error: For security reasons, window.crypto is required to run 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,
};
});
Run Code Online (Sandbox Code Playgroud)
如果我将其导入到我的任何测试中,这似乎是有效的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 }
Run Code Online (Sandbox Code Playgroud)
kca*_*rra 10
希望这对其他人有帮助,但我最终嘲笑了提供者以及我以这种方式使用的其他一些 auth0 模块
jest.mock('@auth0/auth0-react', () => ({
Auth0Provider: ({ children }) => children,
withAuthenticationRequired: ((component, _) => component),
useAuth0: () => {
return {
isLoading: false,
user: { sub: "foobar" },
isAuthenticated: true,
loginWithRedirect: jest.fn()
}
}
}));
Run Code Online (Sandbox Code Playgroud)
这些都在我的setupTests.js文件里
| 归档时间: |
|
| 查看次数: |
3122 次 |
| 最近记录: |