我尝试模拟@auth0/auth0-react
中的useAuth0
,但在返回模拟值时遇到问题。我目前有一个简单的提供程序,使用了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文档中的作用域模块,在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.]
。我已经苦苦挣扎了几个小时,希望能得到帮助。