如何使用 Jest 测试 Reflux 动作 [英] How to test Reflux actions with Jest

查看:16
本文介绍了如何使用 Jest 测试 Reflux 动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

解决方案

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

这篇关于如何使用 Jest 测试 Reflux 动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆