React Js - 酶测试是否触发了setState
React Js - Enzyme test if setState is triggered
我正在使用酶来测试我的反应应用程序。这是我的反应组件:
import React from 'react';
const Child = ({name, setName}) => {
return (
<div>
<button onClick={() => setName('test')}>setName</button>
<h2>Name: {name}</h2>
</div>
);
};
export default Child;
通过单击按钮,我更改了如下传递的 setName
:
function App() {
const [name, setName] = useState();
return (
<div className="App">
<Child setName={setName} name={name}/>
</div>
);
}
export default App;
所以,测试 Child
组件我创建了下一个测试来测试用户单击按钮时应该触发 setName
。
describe('Should test Child component', () => {
const wrapper = (props) => shallow(<Child {...props}/>)
test('should trigger setName', () => {
const mockFun = jest.fn()
const r = wrapper({setName: jest.fn() });
const btn = r.find('button');
btn.simulate('click');
expect(r.props().setName).toHaveBeenCalled()
})
})
运行 我得到的测试:
Error: expect(received).toHaveBeenCalled()
Matcher error: received value must be a mock or spy function
Received has value: undefined
为什么我会收到此错误以及如何使我的测试有效?
我现在无法测试它,但我认为像这样修改它应该可以做到
describe('Should test Child component', () => {
const wrapper = (props) => shallow(<Child {...props}/>)
test('should trigger setName', () => {
const mockFun = jest.fn()
const r = wrapper({setName: mockFun });
const btn = r.find('button');
btn.simulate('click');
expect(mockFun).toHaveBeenCalled()
})
})
也可以将此作为参考同一问题
我正在使用酶来测试我的反应应用程序。这是我的反应组件:
import React from 'react';
const Child = ({name, setName}) => {
return (
<div>
<button onClick={() => setName('test')}>setName</button>
<h2>Name: {name}</h2>
</div>
);
};
export default Child;
通过单击按钮,我更改了如下传递的 setName
:
function App() {
const [name, setName] = useState();
return (
<div className="App">
<Child setName={setName} name={name}/>
</div>
);
}
export default App;
所以,测试 Child
组件我创建了下一个测试来测试用户单击按钮时应该触发 setName
。
describe('Should test Child component', () => {
const wrapper = (props) => shallow(<Child {...props}/>)
test('should trigger setName', () => {
const mockFun = jest.fn()
const r = wrapper({setName: jest.fn() });
const btn = r.find('button');
btn.simulate('click');
expect(r.props().setName).toHaveBeenCalled()
})
})
运行 我得到的测试:
Error: expect(received).toHaveBeenCalled()
Matcher error: received value must be a mock or spy function
Received has value: undefined
为什么我会收到此错误以及如何使我的测试有效?
我现在无法测试它,但我认为像这样修改它应该可以做到
describe('Should test Child component', () => {
const wrapper = (props) => shallow(<Child {...props}/>)
test('should trigger setName', () => {
const mockFun = jest.fn()
const r = wrapper({setName: mockFun });
const btn = r.find('button');
btn.simulate('click');
expect(mockFun).toHaveBeenCalled()
})
})
也可以将此作为参考同一问题