Trafalgar
Trafalgar

Reputation: 401

Spy on imported function

I want to spy on a function that is executed as soon as the file is required. In the example below I want to spy on bar. I have the following files.

code.ts

import {bar} from 'third-party-lib';
const foo = bar()

test.ts

import * as thirdParty from 'third-party-lib';

describe('test', () => {

  let barStub: SinonStub;      

  beforeEach(() => {
     barStub = sinon.stub(thridParty, 'bar')
  })

  it('should work', () => {
    assert.isTrue(bar.calledOnce)
  })

}

The stubing does not work. I think it is a timing issue. Bar gets stubed after it has been executed. The example above works if I wrap the first line in a function and execute that function in my test. But that is not what I want. Anybody an idea on how to stub such methods?

Upvotes: 0

Views: 1019

Answers (2)

deerawan
deerawan

Reputation: 8443

In this matter, we can use proxyquire to stub that third party lib as below:

import * as thirdParty from 'third-party-lib';
const proxyquire = require('proxyquire');

const barStub: SinonStub = sinon.stub();
proxyquire('./your-source-file', {
  'third-party-lib': { bar: barStub } 
});

describe('test', () => {
  it('should work', () => {    
    assert.isTrue(barStub.calledOnce)
  })
}

Ref:

Hope it helps

Upvotes: 2

Maxi Bisurgi
Maxi Bisurgi

Reputation: 353

I think your problem is you are never importing the file where you are doing const foo = bar(). You are just importing bar, thats all! Try importing or requiring your file inside the it block! That should trigger bar() and so, the test should pass!

it('should work', () => {
const foo = require(‘your_foo_file’)
assert.isTrue(bar.calledOnce)
})

Bye!

Upvotes: 0

Related Questions