我有这个档案
// src/history
import { createBrowserHistory } from 'history'
const history = createBrowserHistory();
export default history;
``` `history` 是一个例子 `BrowserHistory` 班级。它在实际代码中使用:
// src/SampleCode.js
import history from '../../history';
export default function SampleCode = () => {
const onClick = () => history.push(/login
);
return (<Button onCLick={onClick}>Click)
}
我想嘲笑一下 `history` 使用另一个类的示例 `MemoryHistory` . 大概是这样的:
// src/sample.test.js
it('should redirect to /login', () => {
const mockHistory = createMemoryHistory();
const historyPush = jest.spyOn(mockHistory, 'push').mockResolvedValue({});
jest.mock('./history', () => mockHistory);
// Click button here
await waitFor(() => expect(historyPush).toBeCalledWith('/login'));
}
但这种方法不起作用: `historyPush` 根本没人打电话
1条答案
按热度按时间gmol16391#
使用jest.domock(modulename、factory、options)确保模拟
./history
模块,然后再导入component
.例如
sample.jsx
:import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
export default history;
```
sample.test.jsx
:测试结果: