提问人:jonteal 提问时间:11/18/2023 更新时间:11/18/2023 访问量:21
如何在 React 单元测试中使用 Vitest 模拟 state、useContext、createContext?
How to mock state, useContext, createContext with Vitest in React unit test?
问:
我正在尝试使用 Vitest 模拟 useContext、createContext。我尝试了很多事情,但还没有运气。这是我的代码和我当前的错误。任何帮助将不胜感激!
切换.test.jsx
import { render, screen } from "@testing-library/react";
import { Toggle } from "../Toggle";
import { vi } from "vitest";
vi.mock("react", () => ({
useContext: vi.fn(),
createContext: vi.fn(),
}));
test("renders the Toggle component", () => {
render(<Toggle />);
screen.debug();
});
context.jsx 实现 darkMode
import { createContext, useReducer } from "react";
export const ThemeContext = createContext();
const INITIAL_STATE = { darkMode: false };
const themeReducer = (state, action) => {
switch (action.type) {
case "TOGGLE":
return { darkMode: !state.darkMode };
default:
return state;
}
};
export const ThemeProvider = (props) => {
const [state, dispatch] = useReducer(themeReducer, INITIAL_STATE);
return (
// Setting the ThemeContext provider for the children within to look to for context
<ThemeContext.Provider value={{ state, dispatch }}>
{props.children}
</ThemeContext.Provider>
);
};
答: 暂无答案
评论