使用Jest Mock Next useRouter测试ItemList组件的方案咨询
前置修正
首先调整测试文件中usePath的导入语句,原hook为命名导出,不要使用默认导入:
把import usePath from '../../hooks/usePath'改为import { usePath } from '../../hooks/usePath'
完整测试实现
你只需要在每个测试用例中给已mock的依赖指定对应返回值即可,最终测试代码如下:
/* eslint-disable camelcase */ /* eslint-env jest */ import { shallow } from 'enzyme'; import React from 'react'; import ItemList from '.'; import { usePath } from '../../hooks/usePath'; import { useRouter } from 'next/router'; import { getBaseURL } from '../../utils/url'; import ITEMS from '../../constants/items'; jest.mock('../../hooks/usePath'); jest.mock('next/router'); jest.mock('../../utils/url'); jest.mock('../../constants/items'); // 每个测试用例执行前清空mock调用记录,避免相互影响 beforeEach(() => { jest.clearAllMocks(); }); describe('ItemList Component', () => { it('should mount without an error', () => { const shallowRender = shallow(<ItemList />); expect(shallowRender.exists()).toBe(true); }); it('should form the page url links including any existing query string', () => { // mock useRouter返回带查询参数的当前路径 useRouter.mockReturnValue({ asPath: '/current/page?from=home&utm_source=test' }); // mock 站点基础前缀 getBaseURL.mockReturnValue('https://test.example.com'); // mock 测试用商品列表 ITEMS.mockReturnValue([ { name: '测试商品1', url: '/items/test-item-1' }, { name: '测试商品2', url: '/items/test-item-2' } ]); const shallowRender = shallow(<ItemList />); // 断言url拼接结果符合预期 expect( shallowRender .find('Item') .at(0) .prop('url') ).toEqual('https://test.example.com/items/test-item-1?from=home&utm_source=test'); }); it('should make the current url active', () => { // mock usePath返回当前访问路径,和第二个商品的url匹配 usePath.mockReturnValue('/items/test-item-2'); // 补充基础mock值 useRouter.mockReturnValue({ asPath: '/items/test-item-2' }); getBaseURL.mockReturnValue('https://test.example.com'); ITEMS.mockReturnValue([ { name: '测试商品1', url: '/items/test-item-1' }, { name: '测试商品2', url: '/items/test-item-2' } ]); const shallowRender = shallow(<ItemList />); // 非当前路径商品active为false expect(shallowRender.find('Item').at(0).prop('active')).toBe(false); // 当前路径商品active为true expect(shallowRender.find('Item').at(1).prop('active')).toBe(true); }); });
如果你的项目是TypeScript,给每个mock调用加上as jest.Mock类型断言即可。
内容的提问来源于stack exchange,提问作者monkeys773
相关产品推荐
相关产品推荐

