不能用Sinon导入文件中的stub函数调用

时间:2016-11-22 16:47:26

标签: javascript node.js ecmascript-6 babeljs

我想断言我的notifier.send函数内部正在调用trackPushNotification trackPushNotification和send函数都在同一个文件中。
我假设我应该使用Sinon来保存callCount以便能够跟踪trackPushNotification属性。当我执行我的测试时,notifier.send似乎根本没有被删除。我搜索了一些东西,显然它与我使用ES6导入/导出的方式有关。我找不到答案,所以我希望有人可以帮我解决这个问题。

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);
});

也进行了快速测试:

<script>
if ($(window).width() > 981){
    function openNav() {
        document.getElementById("mySidenav").style.width = "20%";
        document.getElementById("main1").style.marginLeft = "20%";
    }
    function closeNav() {
        document.getElementById("mySidenav").style.width = "0";
        document.getElementById("main1").style.marginLeft = "0";
    }
}
else if ($(window).width() < 981){
    function openNav() {
        document.getElementById("mySidenav").style.width = "100%";
        document.getElementById("main1").style.display = "none";
    }
    function closeNav() {
        document.getElementById("mySidenav").style.width = "0";
        document.getElementById("main1").style.display = "block";
    }
}
</script>

1 个答案:

答案 0 :(得分:1)

这是一种可以测试它的方法。请注意,在调用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;

    });
相关问题