用Jest模拟delay()RxJS [英] Mock delay() RxJS with Jest
问题描述
是否有一种简单的方法来模拟RxJS的delay()
方法,例如在具有假时间的情况下进行观察?
Is there easy way to mock delay()
method of RxJS in an observable with a fake time for example ?
我有这种方法:
register(user) {
return this._checkLog(user).delay(500).flatMap( ... )
}
当我删除delay()
方法时,我从_register()进行的测试全部成功.
when i remove delay()
method, my tests from _register() all success.
推荐答案
RxJS v6
对于RxJS v6这样的代码:
RxJS v6
For RxJS v6 code like this:
code.js
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';
export const example = of('hello').pipe(
delay(1000)
);
......您可以使用sinon
假计时器,例如这个:
...you can use sinon
fake timers like this:
import * as sinon from 'sinon';
import { example } from './code';
describe('delay', () => {
let clock;
beforeEach(() => { clock = sinon.useFakeTimers(); });
afterEach(() => { clock.restore(); });
it('should delay one second', () => {
const spy = jest.fn();
example.subscribe(spy);
expect(spy).not.toHaveBeenCalled(); // Success!
clock.tick(1000);
expect(spy).toHaveBeenCalledWith('hello'); // Success!
});
});
(请注意,在编写Jest
计时器模拟时,请不要工作,不知道为什么)
(Note that at time of writing Jest
timer mocks don't work, not sure why)
...或者您可以嘲笑delay
这样不做任何事情:
...or you can mock delay
to do nothing like this:
import { delay } from 'rxjs/operators';
import { example } from './code';
jest.mock('rxjs/operators', () => {
const operators = jest.requireActual('rxjs/operators');
operators.delay = jest.fn(() => (s) => s); // <= mock delay
return operators;
});
describe('delay', () => {
it('should delay one second', () => {
const spy = jest.fn();
example.subscribe(spy);
expect(delay).toHaveBeenCalledWith(1000); // Success!
expect(spy).toHaveBeenCalledWith('hello'); // Success!
});
});
RxJS v5
对于RxJS v5这样的代码:
RxJS v5
For RxJS v5 code like this:
code.js
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';
export const example = Observable.of('hello').delay(1000);
...您可以嘲笑delay
这样不做任何事情:
...you can mock delay
to do nothing like this:
import { Observable } from 'rxjs/Observable';
import { example } from './code';
jest.mock('rxjs/add/operator/delay', () => {
const Observable = require('rxjs/Observable').Observable;
Observable.prototype.delay = jest.fn(function () { return this; }); // <= mock delay
});
describe('delay', () => {
it('should delay one second', () => {
const spy = jest.fn();
example.subscribe(spy);
expect(Observable.prototype.delay).toHaveBeenCalledWith(1000); // Success!
expect(spy).toHaveBeenCalledWith('hello'); // Success!
});
});
这篇关于用Jest模拟delay()RxJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!