gpt4 book ai didi

jasmine - 如何使用 Jest 测试回流 Action

转载 作者:行者123 更新时间:2023-12-04 23:20:26 24 4
gpt4 key购买 nike

我在测试 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();
});
});

关于jasmine - 如何使用 Jest 测试回流 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28463189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com