[英]React - componentWillReceiveProps does not execute when component rendered in unit test
New to React, so apologize in advance if this is an ignorant question. React的新手,如果这是一个无知的问题,请提前道歉。 I'm using componentWillReceiveProps to execute a function post-render.
我正在使用componentWillReceiveProps来执行渲染后的功能。 The function is passed in as a prop.
该函数作为道具传递。 Trying to write a unit test to show that the passed in function gets called, but componentWillReceiveProps does not seem to get called when I render the component in my test.
试图编写一个单元测试以显示传递的函数被调用,但是当我在测试中呈现组件时,componentWillReceiveProps似乎没有被调用。 It works when I run the app in the browser, but not in the test.
当我在浏览器中运行应用程序但在测试中无法运行时,它可以工作。
Here's the test: 这是测试:
it('should call function \'selectAll\' when isDefaultSelectAll is true and component is rendered.', ()=> {
const selectAllMock = jest.genMockFunction();
const isDefaultSelectAll = true;
component = TestUtils.renderIntoDocument(<MyComponent {isDefaultSelectAll, selectAllMock} />);;
expect(selectAllMock.mock.calls.length).toBe(1);
});
Here's the code being tested: 这是正在测试的代码:
componentWillReceiveProps(nextProps) {
console.log('GOT HERE');
if (nextProps.isDefaultSelectAll === true) {
nextProps.selectAll();
}
}
Even the log statement does not seem to be hit, and I'm not sure why. 甚至日志语句似乎都没有被击中,我不确定为什么。 Googling has not yielded an answer.
谷歌搜索没有给出答案。
Edit for the first answer - attempted to do a second render as follows, but still not having any luck: 编辑第一个答案-尝试如下进行第二次渲染,但仍然没有运气:
const isDefaultSelectAll = false;
component = TestUtils.renderIntoDocument(<MyComponent {isDefaultSelectAll, selectAllMock} />);
isDefaultSelectAll = true;
component = TestUtils.renderIntoDocument(<MyComponent {isDefaultSelectAll, selectAllMock} />);
componentWillReceiveProps
is not called on the initial render, as stated in the docs: 如文档所述,未在初始渲染上调用
componentWillReceiveProps
:
https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops
Either try to use another lifecycle method or re-render the component in your test. 尝试使用其他生命周期方法或在测试中重新渲染组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.