以下是如何使用 Jest 等工具进行 Mock 的具体方法和示例:一、Mock 基本概念目的:隔离被测试的 Hook,排除外部依赖的干扰核心工具:Jest 提供的 jest.mock()、jest.spyOn /api');jest.spyOn():部分替换对象的方法,保留其他功能 // 只Mock localStorage.getItem,保留其他方法 const getItemSpy = jest.spyOn
Jest提供的mock方法主要有:jest.fn、jest.mock、jest.spyOn。 针对jest.mock与jest.spyOn产生一系列关联的API,如下: 方法 作用 jest.mock 模拟整个模块 jest.spyOn 模拟一个特定功能 jest.clearAllMocks 创建的模拟,其他Mock需要手动恢复 其中jest.restoreAllMocks | .restoreMock 比较特别,只能用于jest.spyOn创建的模拟,因为jest.spyOn包装了原始功能 这里分别使用了jest.spyOn和jest.Mock两个方式对同一个方法进行3种不同编写方式的测试,在实际情况中我们应该选择合适的方法。 expect(mockTestExternalFunc()).toEqual('odd'); expect(fn).toBeCalledTimes(1); }) }) jest.spyOn
spyOn(StoreService, 'listStores').and.callThrough(); // Jasmine spy also allows to call Fake Here we can override the response we previously defined and return a promise with a user object spyOn
1(function SpyOn() { 2 3 const _id = 'spyon-container', 4 _posBuffer = 3; 5 6 function Safari 开源 你可以在这里【https://github.com/eddieherm/spyon】找到源代码,希望你能做得更好!也许你不希望将其作为 IIFE 来实现,或者是去显示其他数据。
Unit Test 再说说单测,一般接口库也主要做这类测试比较多,因为单测不需要实际去访问接口,都是用 mock 的方式去伪造一个数据,而用 Jest 的话就直接 spyOn 去 mock 掉整个请求方法了 afterEach(() => { 3 jest.resetAllMocks() 4 }) 5 test('case 1', async () => { 6 jest.spyOn expect(data).toStrictEqual({ ok: 1 }) 18 }) 19 20 test('case 2', async () => { 21 jest.spyOn client.proxy.a.a.get() 31 32 expect(data).toStrictEqual({ ok: 1 }) 33 34 { 35 jest.spyOn client.proxy.a.b.get() 45 46 expect(data).toStrictEqual({ ok: 1 }) 47 } 48 }) 49 }) COPY 如上,直接用 Jest spyOn
describe('when rendered', () => { it('should fetch a list of tasks', () => { const getSpy = jest.spyOn spyOn 函数返回一个 mock函数。有关其功能的完整列表,请阅读文档。我们的测试检查组件在渲染和运行之后是否从模拟中调用 get函数,并成功执行。 'when rendered', () => { it('should fetch a list of tasks', () => { const fetchSpy = jest.spyOn > { const toDoListInstance = shallow( <ToDoList/> ); const postSpy = jest.spyOn > { const toDoListInstance = shallow( <ToDoList/> ); const postSpy = jest.spyOn
/myFunction';jest.spyOn(myModule, 'myFunction');// 在测试中调用函数myFunction();// 检查函数是否被调用expect(myFunction 使用jest.spyOn代替jest.fn:对于性能敏感的函数,使用jest.spyOn代替jest.fn,因为它更快。
通过 spyOn 函数检查 Mock 模块调用情况 让我们开始 Mock 起来! describe('when rendered', () => { it('should fetch a list of tasks', () => { const getSpy = jest.spyOn 首先通过 jest.spyOn,我们便可以监听一个函数的使用情况,然后使用配套的 toBeCalled Matcher 来判断该函数是否被调用。整体代码十分简洁,同时也保持了很好的可读性。 > { const toDoListInstance = shallow( <ToDoList/> ); const postSpy = jest.spyOn > { const toDoListInstance = shallow( <ToDoList/> ); const postSpy = jest.spyOn
spy = spyOn(remoteService, 'getTodos').and.returnValues([Promise.resolve(datas), Promise.resolve(datas2 第二点就是在模拟的时候,我竟然傻傻的自己去在spec文件中自己去new了BaseDataRemoteService,所以我根本没有办法去执行spyOn(foo, "getBar")这样的模拟,然后就是一直的出错 spy = spyOn(service.remoteService, 'getTodos').and.returnValue(Promise.resolve({content: []})); spyOn(foo, "getBar").and.returnValues("fetched first", "fetched second"); foo.setBar(123); }) it('when the baseUrl is exist and pageNo is exist', async(() => { // 模拟多次进行异步调用时的返回值 spyOn
多选择器的并集:#a-node, .some-other-nodes 2.3.2.3 确认用户操作是否正确响应: 要感知事件是否响应,我们需要使用spyOn方法。 Cancel', showCancel: true }); // 分别监控 ok, onCancel, cancelDialog函数 const spyOk = jest.spyOn (comp.instance,"getData");; const spyCancel = jest.spyOn(comp.instance, 'onCancel'); const spyHide = jest.spyOn(comp.instance, 'cancelDialog'); const ok = comp.querySelector('.ok-btn'); const
也许你使用 jest.mock 模拟了你的 axios HTTP 客户端:jest.spyOn(axios, 'get').mockResolvedValue({ data: 'some mocked 示例:import { flushPromises } from '@vue/test-utils'import axios from 'axios'jest.spyOn(axios, 'get').mockResolvedValue
/BLoginModal/services/wxApi'; // 这种方式设计到代码细节问题需避免使用,如果方法名 getWXSanqrAjax 变更将导致测试用例执行失败 jest.spyOn(wxApis '预发职位', () => { test('预发职位初始化展示', () => { // 模拟store方法,注意这种方法会涉及到代码细节问题,应避免使用,这里只做示意 jest.spyOn service'; describe('视频面试弹窗', () => { beforeEach(() => { // 接口mock参考接口测试一节内容介绍,这里只是快速示意 jest.spyOn beforeAll(() => { jest.useFakeTimers(); }); test("可以在 1000ms 后自动执行函数", () => { jest.spyOn (axios, 'get').mockResolvedValue(resp); // 你也可以使用下面这样的方式: // jest.spyOn(axios, 'get').mockImplementation
unmount', () => { const { unmount } = renderHook(() => useWindowSize()); const removeSpy = jest.spyOn
如下是一个 Jest 测试的示例: it('should open market in browser', () => { const spy = jest.spyOn(Helper, 'openLink 而对于 Componet 中带有 onPress 等的方法,就需要配置 enzyme 来使用: it('test click book', () => { const spy = jest.spyOn
jest中与mock相关的api主要有三个,分别是jest.fn()、jest.mock()、jest.spyOn()。使用它们创建mock函数能够帮助我们更好的测试项目中一些逻辑较复杂的代码。 jest.spyOn() jest.spyOn()方法同样创建一个mock函数,但是该mock函数不仅能够捕获函数的调用情况,还可以正常的执行被spy的函数。 实际上,jest.spyOn()是jest.fn()的语法糖,它创建了一个和被spy的函数具有相同内部代码的mock函数。 Snapshot 快照测试 所谓snapshot,即快照也。
mock 在Jest框架中用来进行mock的方法有很多,主要用到的是jest.fn()和jest.spyOn()。 functionWithCallback(callback) expect(callback.mock.calls.length).toEqual(1) }) }) jest.spyOn 我们源代码中的函数可能使用了另外一个文件或者node_modules中安装的一些依赖,这些依赖可以使用jest.spyOn来进行mock,下面是一个简单的例子: // somewhere/sum.js it('work for positive numbers', () => { // mock validateNumber const validateNumberMock = jest.spyOn implementation validateNumberMock.mockRestore() }) 我们在上面测试代码中引入了源代码使用到的依赖somewhere/validates,这个时候就可以通过jest.spyOn
(container = mount(<Timer />))); it('点击 Start 按钮时调用 startTimer 方法', () => { const spy = jest.spyOn spy).toHaveBeenCalledTimes(1); }); it('点击 Stop 按钮时调用 stopTimer 方法', () => { const spy = jest.spyOn .toHaveBeenCalledTimes(1); }); it('点击 Reset 按钮时调用 resetTimer 方法', () => { const spy = jest.spyOn
, () => { jest.spyOn(appService, 'getHello').mockImplementation(() => 'Hello Nest.js!')
console 是全局对象 global 上的方法,我们没有 require 将其引入,所以 jest.mock 显然处理上有些吃力,这时候 spy 就派上用场了,beforeAll 钩子里直接执行 jest.spyOn 实际上逻辑会比这个复杂的多 那就聊一聊解决方案 mock 数据的随机化,每次测试生成随机的 list 进行测试,现有库 mockjs 强关联测试,证明 map 方法的确执行了,并且参数正确,先 spy spyOn
it('findAllByUserId', async () => { expect(service).toBeDefined(); // 直接返回第一个 user jest.spyOn { const [firstTodo] = mockTodos; it('普通用户只能访问自己的 todo', async () => { jest .spyOn expect(todos).toEqual([firstTodo]); }); it('管理员能访问所有的 todo', async () => { jest.spyOn