How to test Reflux actions with Jest

2019-02-05 08:36发布

I'm having difficulty testing that Reflux actions are triggering correctly in my application, and in fact they do not seem to be working at all with Jest. I have this example test:

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

Which outputs:

● 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)

Even with Jasmine async functions it doesn't seem to be working

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

gives me...

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

Has anybody made this work?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-02-05 09:06

I figured it out! I just needed to use Jest's own methods for fast-forwarding any timers. i.e. just add the line

jest.runAllTimers();

So the working version of my first example would be

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();
  });
});
查看更多
登录 后发表回答