Home > OS >  Deno mock out named import in unit test
Deno mock out named import in unit test

Time:10-23

I would like to make an unit test for a module that is using jsonfile to read the data.

import * as jsonfile from 'https://deno.land/x/jsonfile/mod.ts'

would like to mock out the jsonfile.readJsonSync to return the test data and avoid writing to disk. Can this be done?

Hope this abstract example describes what I want to archive:

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/[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)
})

CodePudding user response:

ES modules cannot be stubbed.

You can however wrap the functionality you want to stub in a class or object and export that and then you can stub methods on it using Sinon.JS or other libraries.

For getting started with Sinon.JS in Deno I suggest checking out Integration with testing libraries | Testing | Manual | Deno which references a sinon_example.ts.

CodePudding user response:

You can substitute modules using an import map.

Just create a local module ./jsonfile.mock.ts containing your mocked functions and export them using the same names as the real module at https://deno.land/x/jsonfile/mod.ts. Then, create an import map with the correct mapping and use it when you run your test:

./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
  • Related