【发布时间】:2020-05-10 00:56:21
【问题描述】:
我不想检查在我的测试中是否使用正确的参数调用了history.push()。
我不确定模拟useHistory()的正确方法是什么
我尝试了this 解决方案。但似乎无法检查push() 是否已被调用。
App.tsx
import React from 'react';
import {useHistory} from 'react-router-dom';
const App: React.FC = () => {
const history = useHistory();
const onClick = () => {
history.push('/anotherPath');
};
return (
<div>
<button onClick={onClick}>click</button>
</div>
);
};
export default App;
App.test.tsx
import React from 'react';
import {render, fireEvent} from '@testing-library/react';
import App from './App';
import {useHistory} from 'react-router-dom'
jest.mock('react-router-dom', () => ({
useHistory: () => ({
push: jest.fn(),
}),
}));
test('renders learn react link', async () => {
const app = render(<App/>);
fireEvent.click(app.getByText('click'));
expect(useHistory().push).toBeCalledWith('/anotherPath');
});
有什么方法可以确保 history.push() 已使用正确的参数调用?
【问题讨论】:
标签: reactjs jestjs react-hooks react-testing-library