2016-11-22 53 views
0

我想聲明在我的notifier.send函數中調用了trackPushNotificationtrackPushNotification和send函數都存在於同一個文件中。
我認爲我應該使用Sinon存根trackPushNotification能夠跟蹤callCount財產。當我執行我的測試時,trackPushNotification似乎並沒有被截斷。我搜索了一些東西,顯然它與我使用ES6導入/導出的方式有關。我找不到答案,所以我希望有人能幫助我解決這個問題。不能在Sinon導入的文件中存根函數調用

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: '[email protected]', 
    }, { 
    username: '[email protected]', 
    }]; 

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

回答

0

這是一種測試方法。請注意,您所需要的聲明,呼籲trackPushNotification

模塊時:

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; 

    }); 
相關問題