无法使用Sinon在导入文件中对函数调用进行桩设。

3
我想要断言在我的notifier.send函数内调用了trackPushNotification两个函数均位于同一文件内。
我认为应该使用Sinon来存根trackPushNotification以便能够跟踪callCount属性。但是当我执行测试时,trackPushNotification似乎根本没有被存根。 我搜索了一些内容,显然这与我使用ES6导入/导出的方式有关。我找不到答案,希望有人能帮我解决这个问题。 notifier.send函数如下:
export const send = (users, notification) => {
  // some other logic

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

我的`notifier.trackPushNotification`函数看起来是这样的:
export const trackPushNotification = (notification, user) => {
  return Analytics.track({ name: 'Push Notification Sent', data: notification.data }, user);
};

我的测试用例如下:

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: 'baz@foo.com',
  }, {
    username: 'john@foo.com',
  }];

  notifier.send(users, notificationStub);

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

我进行了一个快速测试:

// 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);
});
1个回答

2

这是一个测试的方法。请注意,在调用trackPushNotification时需要this语句。

模块:

class notificationSender {
    send(users, notification){        

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

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

}


 export default notificationSender;

测试中的导入

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

测试

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

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

    });

1
谢谢,你提供的提示很有用,调用函数时加上 this 关键字解决了我的问题。没有它,sinon 似乎无法找到应该被 stub 的方法 :) - Benjamin Guttmann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接