如何使用 jest.spyOn 和 React 测试库测试 React 功能组件内的功能
How to test a function inside React functional component using jest.spyOn with React Testing Library
这是一个简单的 React 组件。我正在使用 React 测试库进行单元测试组件,但我无法使用 jest.spyOn()
测试 TestComponent
的 handleClick
函数。有人可以帮忙吗?
组件
import React from 'react';
const Button = (props) => (
<button onClick={props.handleClick}> {props.text}</button>
);
const TestComponent = () => {
const handleClick = () => {
console.log('clicked!');
};
return (
<div>
<Button text="Test Button" handleClick={handleClick} />
</div>
);
};
export default TestComponent;
测试
it('expect spy to be called', () => {
const { getByText } = render(<TestComponent />);
const spy = jest.spyOn(TestComponent, 'handleClick');
const button = getByText('Test Button');
fireEvent.click(button);
expect(spy).toHaveBeenCalled();
});
我遇到的错误如下。我尝试在 jest.spyOn
中使用 TestComponent.prototype
,但这也无济于事。
Cannot spy the handleClick property because it is not a function; undefined given instead
您无法窥探 handleClick
事件处理程序,因为它是在功能范围内定义的,它是 private。
你最好测试组件行为而不是实现,比如event handler内部调用了什么方法,你不应该去mock和assert这些方法是否被调用,而是发生了什么变化,比如发生了什么组件、UI、DOM 树等
但是在你的例子中,handleClick
事件处理程序没有做任何事情,只是调用console.log
,那么你只能断言console.log
是否被调用间接断言handleclick
被调用。
// arrange
const logSpy = jest.spyOn(console, 'log')
// act
// ...
// assert
expect(logSpy).toHaveBeenCalled()
这是一个简单的 React 组件。我正在使用 React 测试库进行单元测试组件,但我无法使用 jest.spyOn()
测试 TestComponent
的 handleClick
函数。有人可以帮忙吗?
组件
import React from 'react';
const Button = (props) => (
<button onClick={props.handleClick}> {props.text}</button>
);
const TestComponent = () => {
const handleClick = () => {
console.log('clicked!');
};
return (
<div>
<Button text="Test Button" handleClick={handleClick} />
</div>
);
};
export default TestComponent;
测试
it('expect spy to be called', () => {
const { getByText } = render(<TestComponent />);
const spy = jest.spyOn(TestComponent, 'handleClick');
const button = getByText('Test Button');
fireEvent.click(button);
expect(spy).toHaveBeenCalled();
});
我遇到的错误如下。我尝试在 jest.spyOn
中使用 TestComponent.prototype
,但这也无济于事。
Cannot spy the handleClick property because it is not a function; undefined given instead
您无法窥探 handleClick
事件处理程序,因为它是在功能范围内定义的,它是 private。
你最好测试组件行为而不是实现,比如event handler内部调用了什么方法,你不应该去mock和assert这些方法是否被调用,而是发生了什么变化,比如发生了什么组件、UI、DOM 树等
但是在你的例子中,handleClick
事件处理程序没有做任何事情,只是调用console.log
,那么你只能断言console.log
是否被调用间接断言handleclick
被调用。
// arrange
const logSpy = jest.spyOn(console, 'log')
// act
// ...
// assert
expect(logSpy).toHaveBeenCalled()