Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Reflux actions with Jest

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?

like image 369
Nathan Harper Avatar asked Feb 11 '23 23:02

Nathan Harper


1 Answers

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();
  });
});
like image 68
Nathan Harper Avatar answered Mar 04 '23 10:03

Nathan Harper