我正在使用React Testing Library来测试我网站的一些功能,在运行测试时,我面临Redux商店初始化的问题。下面是initialState:
const initialState = {
isAuth: false,
loading: localStorage.getItem("authToken") ? true : false,
error: false,
user: {
username: "",
},
};
我已经使用以下代码设置了测试,以将所有内容 Package 在Provider周围:
import { FC, ReactElement } from "react";
import { render, RenderOptions } from "@testing-library/react";
import { Provider } from "react-redux";
import { store } from "../store/store";
const AllTheProviders: FC = ({ children }) => {
return <Provider store={store}>{children}</Provider>;
};
const customRender = (
ui: ReactElement,
options?: Omit<RenderOptions, "wrapper">
) => render(ui, { wrapper: AllTheProviders, ...options });
export * from "@testing-library/react";
export { customRender as render };
然后,在实际测试中,我使用beforeAll(() => window.localStorage.setItem("authToken", "mockToken")
在localStorage中设置令牌。基于loading
状态的值,Login组件应该呈现在我的网站上,但我总是得到 false 作为加载的值。
import { render, screen, waitFor } from "../utils/test-utils";
import App from "../App";
beforeAll(() => window.localStorage.setItem("authToken", "MockAuthToken"));
test("Login page not rendered if a valid auth token is present", async () => {
render(<App />);
//this is to check that the Login component is not rendered
await waitFor(() => expect(screen.queryByText("Sign in")).toBeNull());
await waitFor(() => expect(screen.getByRole("navigation")).toBeDefined(), {
timeout: 5000,
});
});
这是因为Redux存储是在测试期间执行 setItem 函数之前创建的吗?而在浏览器中,当我进入网站时,令牌已经存在,因此预期的行为与测试不相似。
1条答案
按热度按时间7gyucuyw1#
没错我们有一个开放的问题,要求我们在
createSlice
中为initialState
添加一个“惰性初始化函数”重载:https://github.com/reduxjs/redux-toolkit/issues/1024
实际上,我昨晚一直在努力实现这一点,并进行了公关,但有一些关于行为语义变化的担忧:
https://github.com/reduxjs/redux-toolkit/pull/1662
今晚我会再看这个看看我们能想出什么来。