Kunal Kapadia
Kunal Kapadia

Reputation: 3333

Sinon spy not behaving as expected

I have two functions foo and bar in utilityService.js

export function foo() {
    return bar();
}

export function bar() {
    return 1;
}

In my test file i have imported utilityService.js and spied on bar function. I expect callCount of spy to be 1 as foo is called but it is 0. Please suggest if I am missing anything.

import * as utilityService from '../services/utility-service';

let callSpy = sinon.spy(utilityService, 'bar');
expect(utilityService.foo()).to.equal(1);
expect(callSpy.callCount).to.equal(1);

Upvotes: 1

Views: 69

Answers (1)

Oliver
Oliver

Reputation: 4081

From Sinon documentation:

sinon.spy(object, "method") creates a spy for object.method and replaces the original method with the spy.

import creates an object called utilityService which references foo and bar. Sinon replaces utilityService.bar() with its own function. But foo doesn't call utilityService.bar(), but bar() directly. So the call doesn't go through Sinon's replaced function.

I hope it's clear.

Upvotes: 1

Related Questions