【问题标题】:How to test Reflux actions with Jest如何使用 Jest 测试 Reflux 动作
【发布时间】:2015-04-12 08:17:52
【问题描述】:

我在测试 Reflux 操作是否在我的应用程序中正确触发时遇到了困难,实际上它们似乎根本不适用于 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)

即使使用 Jasmine 异步函数,它似乎也不起作用

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]

有人做过吗?

【问题讨论】:

    标签: jasmine jestjs refluxjs


    【解决方案1】:

    我想通了!我只需要使用 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();
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2017-09-14
      • 2015-06-27
      • 2017-12-18
      • 2021-01-06
      • 2017-11-11
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多