我想對用于jsonfile讀取資料的模塊進行單元測驗。
import * as jsonfile from 'https://deno.land/x/jsonfile/mod.ts'
想模擬 jsonfile.readJsonSync 以回傳測驗資料并避免寫入磁盤。這能做到嗎?
希望這個抽象的例子描述了我想要存檔的內容:
索引.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/[email protected]/testing/asserts.ts'
import { readAndReturn } from './index.ts'
const dataFixture = {hello: "word"}
// mock out jsonfile.readJsonSync to return dataFixture and not the actual file content
Deno.test("Reads the data", () => {
assertEquals(readAndReturn(), dataFixture)
})
解決方案
非常感謝@mfulton26 和@jsejcksn 為我指明了正確的方向。
unit.test.importmap.json
{
"imports": {
"https://deno.land/x/jsonfile/mod.ts": "./mocks/jsonfile.ts"
}
}
模擬/jsonfile.ts
import sinon from 'https://cdn.skypack.dev/[email protected]?dts'
const readJsonSync = sinon.stub()
const writeJsonSync = sinon.stub()
export { readJsonSync, writeJsonSync }
index.test.ts
import { readJsonSync as readJsonSyncMock } from './mocks/jsonfile.ts'
Deno.test(
'Reads the data', () => {
const data = ["hello world"]
readJsonSyncMock.withArgs(`./example.json`).returns(data)
assertEquals(readAndReturn(), data)
}
)
uj5u.com熱心網友回復:
您可以使用匯入映射替換模塊。
只需創建一個./jsonfile.mock.ts包含模擬函式的本地模塊,并使用與https://deno.land/x/jsonfile/mod.ts. 然后,使用正確的映射創建匯入映射并在運行測驗時使用它:
./jsonfile.mock.ts:
export function readJsonSync (filePath: string): unknown {
// implement mocked fn
}
// and any other imports you use from the module
./index.importmap.json:
{
"imports": {
"https://deno.land/x/jsonfile/mod.ts": "./jsonfile.mock.ts"
}
}
deno test --import-map=index.importmap.json index.test.ts
uj5u.com熱心網友回復:
ES 模塊不能被存根。
但是,您可以將要存根的功能包裝在類或物件中并匯出它,然后您可以使用Sinon.JS或其他庫存根其上的方法。
要開始在 Deno 中使用 Sinon.JS,我建議查看與測驗庫的集成 | 測驗 | 手冊 | 杰諾其參考一個sinon_example.ts。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/334379.html
