【发布时间】:2021-05-06 15:06:02
【问题描述】:
这是我的测试文件
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;
【问题讨论】:
标签: reactjs redux react-redux jestjs react-testing-library