Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spy on an imported function using Sinon?

Let's say we want to test that a specific function is called by another function using Sinon.

fancyModule.js

export const fancyFunc = () => {
  console.log('fancyFunc')
}

export default const fancyDefault = () => {
  console.log('fancyDefault')
  fancyFunc()
}

fancyModule.test.js

import sinon from 'sinon'
import fancyDefault, { fancyFunc } from '../fancyModule'

describe('fancyModule', () => {
  it('calls fancyFunc', () => {
    const spy = sinon.spy(fancyFunc)
    fancyDefault()
    expect(spy.called).to.be.true
  })
})

When I run this test the actual value is always false. Also, the original function fancyFunc() gets invoked (outputs fancyFunc) instead of being mocked.

like image 747
Marc Avatar asked Jul 14 '17 19:07

Marc


People also ask

How do you spy a function in Sinon?

You can pass this spy where the original function would otherwise be passed when you need to verify how the function is being used. var spy = sinon. spy(object, "method"); Creates a spy for object.

How do you stub a dependency of a module?

To stub a dependency (imported module) of a module under test you have to import it explicitly in your test and stub the desired method. For the stubbing to work, the stubbed method cannot be destructured, neither in the module under test nor in the test.

How do you mock a variable in Sinon?

var sinon = require('sinon'); var start_end = require('./start_end'); describe("start_end", function(){ before(function () { cb_spy = sinon. spy(); }); afterEach(function () { cb_spy. reset(); }); it("start_pool()", function(done){ // how to make timer variable < 1, so that if(timer < 1) will meet start_end.

How do I reset my Sinon stub?

var stub = sinon. The original function can be restored by calling object. method. restore(); (or stub. restore(); ).


2 Answers

You can change the import style, and import your module as an Object like this

import sinon from 'sinon'
import * as myModule from '../fancyModule'

describe('fancyModule', () => {
  it('calls fancyFunc', () => {
    const spy = sinon.spy(myModule, 'fancyFunc');
    myModule.fancyDefault()
    expect(spy.called).to.be.true
  })
})
like image 115
Sebastian Avatar answered Oct 16 '22 21:10

Sebastian


You should use https://github.com/speedskater/babel-plugin-rewire/

import sinon from 'sinon'
import fancyDefault, { __RewireAPI__ } from '../fancyModule'

describe('fancyModule', () => {
  it('calls fancyFunc', () => {
    const spy = sinon.spy()
    __RewireAPI__.__Rewire__('fancyFunc', spy)
    
    fancyDefault()

    expect(spy.called).to.be.true
  })
})

Also, check example: https://github.com/speedskater/babel-plugin-rewire#test-code-2

like image 2
Alexey Kucherenko Avatar answered Oct 16 '22 22:10

Alexey Kucherenko