Deno单元测试中如何mock第三方导入的jsonfile.readJsonSync方法
Deno 单元测试 mock jsonfile 库方法实现方案
问题场景
需要为使用jsonfile库读取数据的模块编写单元测试,模块依赖引入方式如下:
import * as jsonfile from 'https://deno.land/x/jsonfile/mod.ts'
需求是mock jsonfile.readJsonSync 方法,让它直接返回预设的测试数据,不用实际读写磁盘文件。现有抽象示例代码如下:
业务代码 index.ts
import * as jsonfile from 'https://deno.land/x/jsonfile/mod.ts' export function readAndReturn() { return jsonfile.readJsonSync('./example.json') }
初始测试代码 index.test.ts
import { assertEquals } from 'https://deno.land/std@0.112.0/testing/asserts.ts' import { readAndReturn } from './index.ts' const dataFixture = {hello: "word"} // 希望mock jsonfile.readJsonSync返回dataFixture而非实际文件内容 Deno.test("Reads the data", () => { assertEquals(readAndReturn(), dataFixture) })
解决方案
可通过Deno的importmap能力配合sinon打桩实现,步骤如下:
- 新增导入映射配置文件
unit.test.importmap.json:
{ "imports": { "https://deno.land/x/jsonfile/mod.ts": "./mocks/jsonfile.ts" } }
- 新建mock文件
mocks/jsonfile.ts,对外导出打桩后的方法:
import sinon from 'https://cdn.skypack.dev/sinon@11.1.2?dts' const readJsonSync = sinon.stub() const writeJsonSync = sinon.stub() export { readJsonSync, writeJsonSync }
- 修改测试文件
index.test.ts,提前配置打桩方法的返回值:
import { assertEquals } from 'https://deno.land/std@0.112.0/testing/asserts.ts' import { readAndReturn } from './index.ts' import { readJsonSync as readJsonSyncMock } from './mocks/jsonfile.ts' Deno.test( 'Reads the data', () => { const dataFixture = {hello: "word"} readJsonSyncMock.withArgs(`./example.json`).returns(dataFixture) assertEquals(readAndReturn(), dataFixture) } )
- 执行测试时指定导入映射文件即可:
deno test --import-map=unit.test.importmap.json
内容的提问来源于stack exchange,提问作者Norfeldt
相关产品推荐
相关产品推荐

