如何用 Jest 测试回流动作

How to test Reflux actions with Jest

我很难测试 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]

有人做过这个吗?

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