reactjs - redux/react-testing-library 的初始状态对于下一个测试用例保持不变
问题描述
这是我的测试文件
describe("Header", () => {
// passed
it("should render a public header when the user is not authorized", () => {
render(<Header />, {
initialState: {
user: { authorized: false },
},
});
expect(screen.getByTestId("private-header")).toBeInTheDocument();
});
// failed
it("should render a private header when the user is authorized", () => {
render(<Header />, {
initialState: {
user: { authorized: true },
},
});
expect(screen.getByTestId("public-header")).toBeInTheDocument();
});
});
对于第二个测试用例,authorized
值为false
。但我假设它等于true
. 在第一个测试用例之后,初始状态保持不变。
这是我的 test-utils.js 文件
import { render as testingLibraryRender } from "@testing-library/react";
import { Provider } from "react-redux";
import { MemoryRouter } from "react-router-dom";
import configureStore from "../redux/store";
const customRender = (
ui,
{ initialState, store = configureStore(initialState), ...renderOptions } = {}
) => {
// All necessary providers for rendering components
const AllTheProviders = ({ children }) => (
<Provider store={store}>
<MemoryRouter>{children}</MemoryRouter>
</Provider>
);
return testingLibraryRender(ui, { wrapper: AllTheProviders, ...renderOptions });
};
// Re-export everything from testing-library
export * from "@testing-library/react";
// Override render from testing-library with custom render
export { customRender as render };
这是我的 store.js 文件
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
import { setSizes } from '../actions/common/actions';
let store;
window.addEventListener('resize', () => {
if (store) {
store.dispatch(setSizes({
width: window.innerWidth,
height: window.innerHeight,
}));
}
}, { passive: true });
export function configureStore(initialState) {
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
store = store || createStore(
rootReducer,
initialState,
composeEnhancers(
applyMiddleware(thunk),
),
);
return store;
}
export default configureStore;
解决方案
想通了,我在两个测试中使用相同的商店实例,而不是每次都创建一个新商店。
推荐阅读
- selenium - Can we pass priority and enabled from xls sheet for TestNg test?
- python - 在 Pandas 中通过窗口子句实现 MSSQL 的分区
- excel - 如何正确设置POST参数以接收指定日期的持股信息?
- python - Using yield, print and return in python function
- c# - 检查字符串的哪一部分没有被分割
- python-3.x - 使用 BeautifulSoup 代码审查进行网页抓取
- reactjs - react-redux 中的 CRUD,显示来自另一个页面的帖子详细信息
- ios - dispatch_sync 永远不会从块中返回
- python - Python,XML发送带有格式的POST请求
- jquery - Rails 中的 Masonry Jquery - 不刷新页面就无法工作