Dim*_*iwa 7 saga reactjs redux redux-saga
在redux-saga
,我正在使用yield delay(1000);
.在我的单元测试中,我做到了expect(generator.next().value).toEqual(delay(1000));
.
我希望测试通过.
这是我的sagas.js
:
import { delay } from 'redux-saga';
export function* incrementAsync() {
yield delay(1000);
}
Run Code Online (Sandbox Code Playgroud)
这是我的 sagas.test.js
import { delay } from 'redux-saga';
import { incrementAsync } from '../sagas';
describe('incrementAsync Saga test', () => {
it('should incrementAsync', () => {
const generator = incrementAsync();
expect(generator.next().value).toEqual(delay(1000));
});
});
Run Code Online (Sandbox Code Playgroud)
●incrementAsync Saga test>应该incrementAsync
expect(received).toEqual(expected)
Expected value to equal:
{"@@redux-saga/CANCEL_PROMISE": [Function anonymous]}
Received:
{"@@redux-saga/CANCEL_PROMISE": [Function anonymous]}
Difference:
Compared values have no visual difference.
Run Code Online (Sandbox Code Playgroud)
我怎样才能测试redux-saga 延迟?
如果你检查delay
saga效果代码,你会发现它是一个绑定函数:
export const delay = call.bind(null, delayUtil)
Run Code Online (Sandbox Code Playgroud)
因此,如果您导入delay
两个不同的模块,它将是两个不同的功能,没有视觉差异.
您可以在codesandbox示例中查看此内容(请参阅测试选项卡):
const testFunction = () => {};
describe("example bound functions equality test", () => {
it("Two bound functions are not equal", () => {
expect(testFunction.bind(this))
.not.toEqual(testFunction.bind(this));
});
});
Run Code Online (Sandbox Code Playgroud)
要测试你的传奇,你应该模仿你的delay
效果(如果你使用的是Jest);
import { delay } from "redux-saga";
import { incrementAsync } from "../sagas";
jest.mock("redux-saga");
describe("incrementAsync Saga test", () => {
it("should incrementAsync", () => {
const generator = incrementAsync();
expect(generator.next().value).toEqual(delay(1000));
});
});
Run Code Online (Sandbox Code Playgroud)
测试Redux Saga调用的一个好方法是使用call
效果.在这种情况下,您可以按如下方式稍微重构您的传奇:
import { delay } from 'redux-saga';
import { call } from 'redux-saga/effects';
export function* incrementAsync() {
yield call(delay, 1000);
}
Run Code Online (Sandbox Code Playgroud)
然后你会这样测试:
import { delay } from 'redux-saga';
import { call } from 'redux-saga/effects';
describe('incrementAsync', () => {
it('should incrementAsync()', () => {
const generator = incrementAsync();
expect(generator.next().value).toEqual(call(delay, 1000));
});
});
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为yield to的结果call
是一个简单的对象,描述了对delay
函数的调用.不需要任何嘲笑:)
当然还有伟大的redux-saga-test-plan
帮助库.使用它,您的测试将变为以下:
import { testSaga } from 'redux-saga-test-plan';
import { delay } from 'redux-saga';
import { call } from 'redux-saga/effects';
describe('incrementAsync', () => {
it('should incrementAsync()', () => {
testSaga(incrementAsync)
.next()
.call(delay, 1000)
.next()
.isDone();
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5165 次 |
最近记录: |