我需要变异React子组件的props来接收父函数。 更新包装器的功能后,它会更改,但不会影响子组件
//Component
export default Component extends React.Component{
clickFunction(){
console.log('Parent's Click fn');
}
render(){
return(
<div>
<Button onClick={this.clickFunction} data-test-id="button"/>
</div>
)
}
}
// Test
import React from 'react';
import {shallow} from 'enzyme';
const mockClickFunction = jest.fn(() => console.log('Mock Click fn'));
describe('Test Component', () => {
it('Should mutate child prop', () => {
const wrapper = shallow(<Component />);
wrapper.find('[data-test-id="button"]').simulate('click') // Parent's Click fn
console.log(wrapper.instance().clickFunction) // [Function: bound clickFunction]
wrapper.instance().clickFunction = mockClickFunction;
wrapper.update();
console.log(wrapper.instance().clickFunction) // [Function: mockConstructor]
wrapper.find('[data-test-id="button"]').simulate('click') // Parent's Click fn but should be Mock Click fn
})
})
如何更改子组件onClick功能?
答案 0 :(得分:0)
渲染中使用了对原始 clickFunction
的引用。在组件已经浅渲染之后,你不能通过覆盖它来模拟它。
在调用 Component.prototype.clickFunction
之前尝试监视 shallow
。
例如
index.jsx
:
import React from 'react';
export default class Component extends React.Component {
clickFunction() {
console.log("Parent's Click fn");
}
render() {
return (
<div>
<button onClick={this.clickFunction} data-test-id="button" />
</div>
);
}
}
index.test.tsx
:
import { shallow } from 'enzyme';
import React from 'react';
import Component from '.';
describe('55611882', () => {
it('should pass', () => {
const mockClickFunction = jest
.spyOn(Component.prototype, 'clickFunction')
.mockImplementation(() => console.log('Mock Click fn'));
const wrapper = shallow(<Component />);
wrapper.find('[data-test-id="button"]').simulate('click');
expect(mockClickFunction).toBeCalledTimes(1);
mockClickFunction.mockRestore();
});
});
测试结果:
PASS examples/55611882/index.test.jsx (13.099 s)
55611882
✓ should pass (81 ms)
console.log
Mock Click fn
at examples/55611882/index.test.jsx:9:41
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 75 | 100 | 50 | 75 |
index.jsx | 75 | 100 | 50 | 75 | 5
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.416 s