【发布时间】:2020-01-22 08:34:13
【问题描述】:
我在测试 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"}) 被触发,但我不明白如何在我的测试中测试和接收调度。我知道我必须在我的上下文中修改调度值 (value={[{value}, function to write]},但我被卡住了:(
有人可以帮我吗?
编辑:
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
【问题讨论】:
-
您能否展示您的 app.js 文件,以便我们查看您使用的提供程序,以及您调度操作的上下文提供程序文件?还有整个组件和测试,因为测试很棘手,我需要查看所有帮助:)
标签: javascript reactjs testing react-hooks react-testing-library