我想测试一个传奇,它产生了一个以函数作为模式的take效果。
export function* mySaga(myAction: {
type: string;
}): Generator<TakeEffect, boolean, { type: string }> {
const { type: actionType } = (yield take(
(action: any) => action.type === myAction.type,
)) as { type: string };
return actionType === myAction.type;
}使用的测试如下:
it('Should test mySaga', () => {
testSaga(mySaga, { type: 'myActionType' }).next().take().next().finish();
});但我得到了以下错误:
SagaTestError:
Assertion 1 failed: take effects do not match
Expected
--------
{ '@@redux-saga/IO': true,
combinator: false,
type: 'TAKE',
payload: { pattern: '*' } }
Actual
------
{ '@@redux-saga/IO': true,
combinator: false,
type: 'TAKE',
payload: { pattern: [Function] } }我还没有找到如何断言接受函数模式而不是字符串的a获取效果。有人能帮帮我吗?
发布于 2021-06-23 07:37:11
因为您将匿名函数传递给take效果创建者。我们不能使用所需的模块在测试用例中获得这个匿名函数。
您可以使用检查一般断言助手。
如果您的传奇产生了一种不确定类型的值,或者一些不容易被效果断言或其他一般断言覆盖的东西,那么您可以使用
inspect检索实际产生的值,并使用您喜欢的断言库执行自己的断言。
这样我们就可以得到yield take((action: any) => action.type === myAction.type)的返回效果。然后,断言这一效果。
例如(使用jestjs作为测试框架)
saga.ts
import { TakeEffect, take } from 'redux-saga/effects';
export function* mySaga(myAction: { type: string }): Generator<TakeEffect, boolean, { type: string }> {
const { type: actionType } = (yield take((action: any) => action.type === myAction.type)) as { type: string };
console.log('actionType: ', actionType);
return actionType === myAction.type;
}saga.test.ts
import { testSaga } from 'redux-saga-test-plan';
import { TakeEffect } from 'redux-saga/effects';
import { mySaga } from './saga';
describe('63523200', () => {
it('should pass', () => {
testSaga(mySaga, { type: 'myActionType' })
.next()
.inspect<TakeEffect>((yieldedValue) => {
expect(yieldedValue.payload.pattern).toEqual(expect.any(Function));
// test this anonymous function
expect((yieldedValue.payload.pattern as Function)({ type: 'myActionType' })).toBeTruthy();
expect((yieldedValue.payload.pattern as Function)({ type: 'hisActionType' })).toBeFalsy();
})
.next({ type: 'otherActionType' })
.isDone();
});
});单元测试结果:
PASS src/stackoverflow/63523200/saga.test.ts
63523200
✓ should pass (23 ms)
console.log
actionType: otherActionType
at src/stackoverflow/63523200/saga.ts:5:11
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
saga.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.809 s, estimated 3 shttps://stackoverflow.com/questions/63523200
复制相似问题