[英]How to test with Jest that ReactDOM.render has been called when it has been wrapped in a conditional?
I have the following react component and it conditionally calls ReactDOM.render
if root === true
in order to satisfy flow
: 我有以下react组件,并且如果
root === true
,它ReactDOM.render
条件地调用ReactDOM.render
以满足flow
:
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
const root = document.getElementById('root')
if (root !== null) {
ReactDOM.render(<App />, root)
}
The problem is that this test no longer equals true, presumably because the conditional wrapping needs to be mocked as true or something but I can't figure it out. 问题在于该测试不再等于true,大概是因为需要将条件包装模拟为true或类似的东西,但我无法弄清楚。
import ReactDOM from 'react-dom'
jest.mock('react-dom')
require('../index')
test('Renders the application', () => {
expect(ReactDOM.render).toBeCalled()
})
How do I need to update my test to check that ReactDOM.render
is called? 我该如何更新测试以检查
ReactDOM.render
是否被调用?
I think this test case is redundant since you will have to mock document and render function so basically what you are testing is just the conditional. 我认为该测试用例是多余的,因为您将不得不模拟文档和渲染功能,因此基本上您所测试的只是有条件的。 But there could be similar use case.
但是可能会有类似的用例。 You should make following changes to code.
您应该对代码进行以下更改。
function renderToDOM() {
if (root !== null) {
ReactDOM.render(<App />, root)
}
}
renderToDOM();
export {renderToDOM};
By making this change we will able to write a clean test and test only this piece of code independently. 通过进行此更改,我们将能够编写干净的测试,并仅独立测试这段代码。 Following is the test case which worked for me.
以下是对我有用的测试案例。 Had to mock ReactDOM.render as well as document.getElementById to get the test case working.
必须模拟ReactDOM.render以及document.getElementById才能使测试用例正常工作。
import ReactDOM from "react-dom";
import { mock } from "jest";
import { renderToDOM } from "./index";
describe("test ReactDOM.render", () => {
const originalRender = ReactDOM.render;
const originalGetElement = global.document.getElementById;
beforeEach(() => {
global.document.getElementById = () => true;
ReactDOM.render = jest.fn();
});
afterAll(() => {
global.document.getElementById = originalGetElement;
ReactDOM.render = originalRender;
});
it("should call ReactDOM.render", () => {
renderToDOM();
expect(ReactDOM.render).toHaveBeenCalled();
});
});
Following is the code sandbox link where you can see this test running and test cases are passing. 以下是代码沙箱链接,您可以在其中看到此测试正在运行并且测试用例正在通过。 https://codesandbox.io/s/7wr0k7qmq
https://codesandbox.io/s/7wr0k7qmq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.