我试图模拟出useAuth0
从@auth0/auth0-react
和正在运行到返回模拟值的问题。我目前有一个简单的提供程序,它使用useAuth0
import React, { createContext } from 'react';
import { useAuth0 } from "@auth0/auth0-react";
export const UserContext = createContext();
export const UserProvider = props => {
const {
isLoading
} = useAuth0();
return (
props.children
)
};
render
在我的测试中,此提供程序用于自定义函数
// 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 your own reducer
import applicationsReducer from "../app/slices/applications.slice";
import { UserProvider } from "../user-context";
function render(
ui,
{
initialState,
mock,
store = createStore(applicationsReducer, initialState),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return <Provider store={store}>
<MockedProvider mocks={mock} addTypename={false}>
<UserProvider>{children}</UserProvider>
</MockedProvider>
</Provider>
}
return rtlRender(ui, { wrapper: Wrapper, ...renderOptions })
}
// re-export everything
export * from '@testing-library/react'
// override render method
export { render }
为了模拟它,我使用 jest 的作用域module文档设置了一个 mocks 文件夹
--src
--__mocks__
--@auth0
--auth0-react.js
该模拟的代码如下所示
export const withAuthenticationRequired = jest.fn().mockImplementation((component, _) => {
return component
})
export const useAuth0 = jest.fn().mockReturnValue({
error: null,
isAuthenticated: true,
isLoading: true,
user: {},
})
在withAuthenticationRequired
模拟工作正常,但是useAuth0
不断抛出的错误
Error: Uncaught [TypeError: Cannot destructure property 'isLoading' of '(0 , _auth0React.useAuth0)(...)' as it is undefined.]
我一直在挣扎与此几个小时,和任何帮助,将不胜感激。