如何解决使用redux-saga-test-plan进行断言,该函数采用一个函数作为模式,给出“效果不匹配”错误
我想测试一个产生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,payload: { pattern: [Function] } }
我无法找到如何断言采用函数模式而不是字符串的take效果。有人可以帮我吗?
解决方法
由于您将匿名函数传递给 take
效果创建者。我们在使用required模块的测试用例中无法得到这个匿名函数。
您可以使用 inspect 通用断言助手。
如果您的 saga 产生非确定性类型的值或效果断言或其他一般断言不易涵盖的内容,那么您可以使用 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 s
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。