我在测试useContext挂钩上的分配值时遇到麻烦。
我有一个简单的组件:
Connexion.tsx :
const Connexion = () => {
const [user, userDispatch] = React.useContext(userContext);
//...other stuff
}
我正在检查测试中调度的值,所以我的测试文件是:
Connexion.test.jsx :
...
const renderConnexion = () => {
return render(
<userContext.Provider
value={[
{
connecte: true,
// ...other stuff
},
() => {}
]}
>
<Connexion />
</userContext.Provider>
);
};
...
test("Déconnexion", async () => {
const component = renderConnexion();
fireEvent.mouseDown(component.getByTestId("deconnexion"));
});
在mouseDown事件上,将触发dispatchUser({type:“ REMOVE”}),但是我不知道如何在测试中测试和接收调度。我知道我必须在我的上下文中修改调度值(值= {[{值},要编写的功能]},但我被困住了:(
有人可以帮助我吗?
编辑:
Reducers :
export const userReducer = (state: State, action: Action) => {
switch (action.type) {
case "UPDATE":
return {
connecte: true,
prenom: action.user.prenom,
nom: action.user.nom,
email: action.user.email,
grade: action.user.grade
};
case "REMOVE": {
return { connecte: false };
}
default:
throw new Error();
}
};
export const userInit = { connecte: false };
App :
const App = () => {
const [user, userDispatch] = React.useReducer(userReducer, userInit);
return (
<S.ConteneurGlobal>
<userContext.Provider value={[user, userDispatch]}>
// ...other stuff
}
感谢您的帮助:D
答案 0 :(得分:1)
您应该模拟userDispatch
函数
import React from 'react';
import {
render,
cleanup,
fireEvent,
} from '@testing-library/react';
// other imports here eg: userContext.Provider
afterEach(() => {
cleanup();
jest.clearAllMocks();
});
const renderConnexion = (mockUserDispatch, mockUser) => {
return render(
<userContext.Provider
value={[
{
userDispatch: mockUserDispatch
// mock other values here by taking them as a parameter
// for example, for user also take it as parameter
user: mockUser
},
() => {}
]}
>
<Connexion />
</userContext.Provider>
);
};
it('calls dispatchUser when mouseD', () => {
// Given
const mockedUserDispatch = jest.fn();
const mockUser = {}
// When
const component = renderConnexion(mockedUserDispatch, mockUser);
fireEvent.mouseDown(component.getByTestId("deconnexion"));
// Then
expect(mockedUserDispatch).toHaveBeenCalled();
});