【发布时间】:2021-11-01 18:53:42
【问题描述】:
我正在尝试测试一个函数被调用
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,你可以在你的测试中传递它,然后调用 mock 函数。 -
我已经看到这样做了——几乎在每个例子中。我会修改我的代码以适应测试。我可以,但对我来说似乎是错误的。
标签: reactjs function jestjs mocking react-testing-library