Lef*_*eff 4 reactjs jestjs react-test-renderer
我正在使用react-test-rendererJest 来测试 React 组件。但是,如果我像这样测试 react-mui 模态对话框:
describe('Dashboard', function () {
let dashboard;
beforeEach(async () => {
testRenderer = TestRenderer.create(<MemoryRouter><Route component={Dashboard} /></MemoryRouter>);
dashboard = testRenderer.root.findByType(Dashboard);
await waitForExpect(() => expect(dashboard.instance.state.hasLoaded).toBeTruthy());
});
it('opens dialog on clicking the new class', async () => {
const button = testRenderer.root.findByType(Button);
expect(dashboard.instance.state.showDialog).toBeFalsy();
button.props.onClick();
expect(dashboard.instance.state.showDialog).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
但是,然后我收到一个错误:
错误:失败:“错误:未捕获'警告:提供了无效的容器。这可能表明除了测试渲染器之外,正在使用另一个渲染器。(例如,ReactTestRenderer 树中的 ReactDOM.createPortal。)这是不支持。%s'
我应该如何测试然后响应门户以使此测试有效?
尝试将其放入您的测试中:
beforeAll(() => {
ReactDOM.createPortal = jest.fn((element, node) => {
return element
})
});
Run Code Online (Sandbox Code Playgroud)
基于 Oliver 的回答,但对于 TypeScript 用户:
describe("Tests", () => {
const oldCreatePortal = ReactDOM.createPortal;
beforeAll(() => {
ReactDOM.createPortal = (node: ReactNode): ReactPortal =>
node as ReactPortal;
});
afterAll(() => {
ReactDOM.createPortal = oldCreatePortal;
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3570 次 |
| 最近记录: |