问题描述
以下测试用例将正确返回数据,但 JEST 显示为失败。测试是使用 TestScheduler
玩笑结果
expect(received).toEqual(expected) // deep equality
- Expected
+ Received
- Array [
- Object {
- "frame": 3,- "notification": Notification {
- "error": undefined,- "hasValue": true,- "kind": "N",- "value": Object {
- "type": "INITIALIZED",- },- },- },- ]
+ Array []
import { ofType } from 'redux-observable';
import { mergeMap,map,tap } from 'rxjs/operators';
import { of,from } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
describe('routechange epic',() => {
const testScheduler = new TestScheduler((actual,expected) => {
expect(actual).toEqual(expected);
});
it('check apollo',() => {
const dependencies = {
apolloClient: {
mutate: ({ mutation,variables }: { mutation: any,variables: any }) =>
Promise.resolve({
data: { param: 'testA' }
})
},};
const initializeOrg = (action$,state$,{ apolloClient }) =>
action$
.pipe(
ofType('START'),tap(act => console.log('---AAA',act)),mergeMap(action =>
from(
apolloClient.mutate({
mutation: `something`,variables: {
orgId: (action as any).params || ''
}
})
)
.pipe(
tap(x => console.log('----x',x)),map(response => ({
type: 'INITIALIZED',response,}))
)
)
);
testScheduler.run(({ hot,cold,expectObservable }) => {
const action$ = hot('-a',{
a: { type: 'START',params: 'SomethingA' }
});
const state$ = null;
const output$ = initializeOrg(action$,dependencies);
expectObservable(output$).toBe('---a',{
a: {
type: 'INITIALIZED'
}
})
});
});
});
解决方法
我们不能使用 Promise.resolve
作为某人的评论。
它现在可以与如下所示的冷 observable 一起使用。
import { ofType } from 'redux-observable';
import { mergeMap,map,tap,toArray,take } from 'rxjs/operators';
import { of,from } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
describe('routechange epic',() => {
it('check apollo',async () => {
const testScheduler = new TestScheduler((actual,expected) => {
expect(actual).toEqual(expected);
});
const initializeOrg = (action$,state$,{ apolloClient }) =>
action$
.pipe(
ofType('START'),tap(act => console.log('---AAA',act)),mergeMap(action =>
from(
apolloClient.mutate({
mutation: `something`,variables: {
orgId: (action as any).params || ''
}
})
)
.pipe(
tap(x => console.log('----x',x)),map(response => ({
type: 'INITIALIZED',response,}))
)
)
);
testScheduler.run(({ hot,cold,expectObservable }) => {
const action$ = hot('-a',{
a: { type: 'START',params: 'SomethingA' }
});
const state$ = null;
const dependencies = {
apolloClient: {
mutate: ({ mutation,variables }: { mutation: any,variables: any }) =>
cold('--a|',{
a: { data: { param: 'testA' } }
})
},};
const output$ = initializeOrg(action$,dependencies);
expectObservable(output$).toBe('---a',{
a: {
type: 'INITIALIZED',response: {
data: { param: 'testA' }
}
}
})
});
});
});