我正在尝试测试一个函数是否被调用
import React from 'react';
import { render, cleanup, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import MyForm from './MyForm';
afterEach(cleanup);
const testFunction = jest.fn();
test('my form', () => {
const { getByTestId } = render(<MyForm />);
const myButton = getByTestId('submit-button');
expect(myButton.tagName).toBe('BUTTON');
fireEvent.click(myButton)
expect(testFunction).toHaveBeenCalledTimes(1)
});
我遇到的问题是似乎没有绑定到模拟函数,但它确实调用了组件中的函数。
import React from 'react';
export default function myForm() {
function testFunction() {
console.log('hello from inside');
}
return (
<div>
<form onSubmit={testFunction}>
<input type="text" />
<button type="submit" data-testid="submit-button">submit</button>
</form>
</div>
);
}
如何调用模拟函数而不是“真实”函数。
expect(jest.fn()).toHaveBeenCalledTimes(1)
Expected mock function to have been called one time, but it was called zero times.
testFunction
是否必须(隐藏)在 myForm 组件内部?如果它是一个 prop,你可以在测试中传递它,然后模拟函数将被调用。 - tromgy