guidsen
guidsen

Reputation: 2393

Cannot stub function call in imported file with Sinon

I want to assert that the trackPushNotification is being called inside my notifier.send function. Both the trackPushNotification and send function live inside the same file.
I assumed I should stub the trackPushNotification using Sinon to be able to keep track of the callCount property. When I execute my test, the trackPushNotification doesn't seem to get stubbed at all. I've searched some things and apparently it has something to do with the way I'm using ES6 import/exports. I couldn't find an answer so I hope someone can help me with this issue.

The notifier.send function looks like this:

export const send = (users, notification) => {
  // some other logic

  users.forEach(user => trackPushNotification(notification, user));
};

My notifier.trackPushNotification function looks like this:

export const trackPushNotification = (notification, user) => {
  return Analytics.track({ name: 'Push Notification Sent', data: notification.data }, user);
};

My test case looks like this:

it('should track the push notifications', () => {
  sinon.stub(notifier, 'trackPushNotification');

  const notificationStub = {
    text: 'Foo notification text',
    data: { id: '1', type: 'foo', track_id: 'foo_track_id' },
  };

  const users = [{
    username: '[email protected]',
  }, {
    username: '[email protected]',
  }];

  notifier.send(users, notificationStub);

  assert.equal(notifier.trackPushNotification.callCount, 2);
});

Also did a quick test:

// implementation.js
export const baz = (num) => {
  console.log(`blabla-${num}`);
};

export const foo = (array) => {
  return array.forEach(baz);
};

// test.js
it('test', () => {
  sinon.stub(notifier, 'baz').returns(() => console.log('hoi'));

  notifier.foo([1, 2, 3]); // outputs the blabla console logs

  assert.equal(notifier.baz.callCount, 3);
});

Upvotes: 3

Views: 778

Answers (1)

Hosar
Hosar

Reputation: 5292

This is one way you can test it. Please notice that you need the this statement when calling trackPushNotification

module:

class notificationSender {
    send(users, notification){        

        users.forEach(user => this.trackPushNotification(notification, user));        
    }

    trackPushNotification(notification, user){
        console.log("some");
    }

}


 export default notificationSender;

import on test

import notificationSender from './yourModuleName';<br/>

test

    it('notifications', function(){
        let n = new notificationSender();        
        sinon.spy(n,'trackPushNotification');

        n.send(['u1','u2'],'n1');
        expect(n.trackPushNotification.called).to.be.true;

    });

Upvotes: 2

Related Questions