我有一个<UserProvider />
提供上下文的组件,login
它的值中有一个方法。在我的测试中,我想检查该方法是否已被调用。如果来自上下文,我如何检查以确保在我的测试中调用了这个方法?我试过使用spyOn和mock方法,但我无法让它们工作。
这是我UserProvider
提供上下文的组件。
import React, { useState, useContext, createContext } from 'react'
const UserContext = createContext()
function UserProvider({ children }) {
const [user, setUser] = useState(null)
const login = user => setUser(user)
return <UserContext.Provider value={{ user, login }}>{children}</UserContext.Provider>
}
const useUser = () => useContext(UserContext)
export { UserProvider, useUser }
这是我的Login
组件,使用来自UserProvider
(via useUser
)的上下文
import React from 'react'
import { useUser } from './UserProvider'
function Login() {
const { login } = useUser()
const handleSubmit = async e => {
e.preventDefault()
// I need to make sure this method is being called in my test.
login({ name: 'John Doe' })
}
return (
<form onSubmit={handleSubmit}>
<button>Login</button>
</form>
)
}
export default Login
这是我的Login
测试
import React from 'react'
import { render, fireEvent } from '@testing-library/react'
import Login from './Login'
import { UserProvider, useUser } from './UserProvider'
// Is this correct?
jest.mock('./UserProvider', () => ({
useUser: jest.fn(() => ({
login: jest.fn()
}))
}))
it('should log a user in', () => {
const { getByText } = render(
<UserProvider>
<Login />
</UserProvider>
)
const submitButton = getByText(/login/i)
fireEvent.click(submitButton)
// How can I make this work?
const { login } = useUser()
expect(login).toHaveBeenCalledTimes(1)
})