我一直在尝试用shallow
渲染组件,该组件由enzyme
提供。
组件正在使用useHistory
中的react-router-dom
。
const baseMatch: match<{ id: string }> = { /* path, url, params */};
const location = createLocation(baseMatch.url);
describe('MyComponent', () => {
const baseProps = {
history: createMemoryHistory(),
location: createLocation(baseMatch.url),
match: baseMatch
};
beforeEach(() => {
jest.mock('react-router-dom', () => ({
useHistory: jest.fn()
}));
});
afterEach(() => { jest.clearAllMocks() });
it('renders blah blah', () => {
const wrapper = shallow(<MyComponent {...baseProps} />);
// testing MyComponent here...
});
我指的是this post,并以相同的方式放入jest.mock
。
但是,结果为TypeError: Cannot read property 'history' of undefined
。
控制台说:
MyComponent › renders blah blah
TypeError: Cannot read property 'history' of undefined
24 | const MyComponent = (props: IProps) => {
25 | console.log('useHistory', useHistory);
> 26 | let history = useHistory();
奇怪的是,上面第25行的console.log
打印了useHistory
的实现(换句话说,它不是未定义的。)>
显然,useHistory
没有被嘲笑。我怀疑useHistory
不能被shallow
嘲笑(在上面的帖子中,发布者使用的是mount()
)。
但是,我不确定100%,因为从shallow
和useHistory
的文档中找不到enzyme
是否与react-router
兼容。
是否可以将shallow
与useHistory
一起使用?任何建议将不胜感激。
我一直在尝试用酶提供的组件变浅。该组件正在使用来自react-router-dom的useHistory。 const baseMatch:匹配= {/ * ...
从docs: