jeudi 25 juillet 2019

How to stub a libary function in JavaScript

For example, if I have main.js calling a defined in src/lib/a.js, and function a calls node-uuid.v1, how can I stub node-uuid.v1 when testing main.js?

main.js

const a = require("./src/lib/a").a

const main = () => {
  return a()
}

module.exports = main

src/lib/a.js

const generateUUID = require("node-uuid").v1

const a = () => {
  let temp = generateUUID()
  return temp
}

module.exports = {
  a
}

tests/main-test.js

const assert = require("assert")
const main = require("../main")
const sinon = require("sinon")
const uuid = require("node-uuid")

describe('main', () => {
  it('should return a newly generated uuid', () => {
    sinon.stub(uuid, "v1").returns("121321")

    assert.equal(main(), "121321")
  })
})

The sinon.stub(...) statement doesn't stub uuid.v1 for src/lib/a.js as the above test fails.

Is there a way to globally a library function so that it does the specified behavior whenever it gets called?

Aucun commentaire:

Enregistrer un commentaire