2015-02-11 78 views
4

我很難測試迴流操作在我的應用程序中正確觸發,事實上他們似乎根本不用Jest工作。我有這樣的例子測試:如何用Jest測試迴流行爲

jest.autoMockOff(); 

describe('Test', function() { 
    it('Tests actions', function() { 
    var Reflux = require('../node_modules/reflux/index'); 

    var action = Reflux.createAction('action'); 
    var mockFn = jest.genMockFn(); 

    var store = Reflux.createStore({ 
     init: function() { 
     this.listenTo(action, this.onAction); 
     }, 
     onAction: function() { 
     mockFn(); 
     } 
    }); 

    action('Hello World'); 
    expect(mockFn).toBeCalled(); 
    }); 
}); 

,輸出:

● Test › it Tests actions 
    - Expected Function to be called. 
    at Spec.<anonymous> (__tests__/Test.js:20:20) 
    at Timer.listOnTimeout [as ontimeout] (timers.js:112:15) 

即使茉莉花異步功能似乎並不奏效

jest.autoMockOff(); 

describe('Test', function() { 
    it('Tests actions', function() { 
    var Reflux = require('../node_modules/reflux/index'); 

    var action = Reflux.createAction('action'); 
    var mockFn = jest.genMockFn(); 

    var flag = false; 

    var store = Reflux.createStore({ 
     init: function() { 
     this.listenTo(action, this.onAction); 
     }, 
     onAction: function() { 
     mockFn(); 
     flag = true; 
     } 
    }); 

    runs(function() { 
     action(); 
    }); 

    waitsFor(function() { 
     return flag; 
    }, 'The action should be triggered.', 5000); 

    runs(function() { 
     expect(mockFn).toBeCalled(); 
    }); 
    }); 
}); 

給我...

FAIL __tests__/Test.js (6.08s) 
● Test › it Tests actions 
    - Throws: [object Object] 

有沒有人提出他的工作?

回答

8

我想通了!我只需要使用Jest自己的方法來快速轉發任何定時器。即只需添加一行

jest.runAllTimers(); 

所以我的第一個例子中的工作版本將

jest.autoMockOff(); 

describe('Test', function() { 
    it('Tests actions', function() { 
    var Reflux = require('../node_modules/reflux/index'); 

    var action = Reflux.createAction('action'); 
    var mockFn = jest.genMockFn(); 

    var store = Reflux.createStore({ 
     init: function() { 
     this.listenTo(action, this.onAction); 
     }, 
     onAction: function() { 
     mockFn(); 
     } 
    }); 

    action('Hello World'); 

    jest.runAllTimers(); 

    expect(mockFn).toBeCalled(); 
    }); 
});