[英]Enzyme & React router: How to shallow render a component with useHistory
我一直在嘗試的是用shallow
渲染組件,這是由enzyme
提供的。
該組件正在使用react-router-dom
useHistory
。
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...
});
我參考了這篇文章,並以同樣的方式放置了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
沒有被嘲笑。 我懷疑不能用shallow
來嘲笑useHistory
(在上面的帖子中,海報使用的是mount()
)。
但是,我不是 100% 確定,因為我無法從enzyme
和react-router
的文檔中找到shallow
是否與useHistory
兼容。
是否可以在useHistory
使用shallow
? 任何建議將被認真考慮。
從文檔:
注意:為了正確模擬,Jest 需要 jest.mock('moduleName') 與 require/import 語句在同一范圍內。
因此,不要在beforeEach
中beforeEach
react-router-dom - 嘗試將其置於頂級范圍:
jest.mock('react-router-dom', () => ({
useHistory: jest.fn()
}));
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
};
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.