我对 React 还很陌生,所以请原谅我的无知。我有一个组件:
const Login: FunctionComponent = () => {
const history = useHistory();
//extra logic that probably not necessary at the moment
return (
<div>
<form action="">
...form stuff
</form>
</div>
)
}
当尝试编写笑话/酶测试时,我编写的一个测试用例失败并出现以下错误
` › 遇到声明异常
TypeError: Cannot read property 'history' of undefined`
我尝试使用 jest 来模拟 useHistory,如下所示:
jest.mock('react-router-dom', () => ({
useHistory: () => ({ push: jest.fn() })
}));
但这没有任何作用:(并且我得到了同样的错误。任何帮助将不胜感激
UPDATE:
所以我想通了。我走在正确的道路上,为useHistory()
钩子,我定义在错误的地方。需要在测试方法的范围之外定义模拟(至少对于 useHistory),例如:
import { shallow } from 'enzyme';
import React from 'react';
import Login from './app/componets/login.component';
jest.mock('react-router', () => ({
...jest.requireActual('react-router'),
useHistory: () => ({ push: jest.fn() })
}));
/**
* Test suite describing Login test
describe('<LoginPage>', () => {
test('should test something', () => {
//expect things to happen
});
})
通过上述测试运行,不会因历史未定义而失败。