Wenshan
Wenshan

Reputation: 700

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?

Upvotes: 0

Views: 1620

Answers (2)

Borja Tur
Borja Tur

Reputation: 817

Bear in mind that node-uuid is deprecated as you can see by this warning

[Deprecation warning: The use of require('uuid') is deprecated and will not be supported after version 3.x of this module. Instead, use require('uuid/[v1|v3|v4|v5]') as shown in the examples below.]

About how to stub that for testing would be a bit more harder than before as actually there is no an easy way to mock a standalone function using sinon

Creating a custom module

//custom uuid
module.exports.v1 = require('uuid/v1');

Requiring uuid from the custom module in your project

const uuid = require('<path_to_custom_module>');

Sinon.stub(uuid, 'v1').returns('12345');

Upvotes: 0

antonku
antonku

Reputation: 7665

You should configure the stub before importing the main module. In this way the module will call the stub instead of the original function.

const assert = require("assert")
const sinon = require("sinon")
const uuid = require("node-uuid")

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

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

Upvotes: 1

Related Questions