【发布时间】:2019-09-21 13:36:50
【问题描述】:
我正在为我的 effect.ts 文件编写单元测试。但由于某种原因,即使我将期望语句更改为调度 ContactInfoFailed 操作,它也会通过。我的测试文件中的订阅有问题吗?我无法弄清楚这到底是什么原因!或者如果有更好的方法来编写这个测试? 请在下面找到我的效果和它的测试用例。
// effects.ts
import { Actions, Effect, ofType } from '@ngrx/effects';
import { ContactTriageService } from '../views/contact-triage/contact-triage.service';
import {
CONTACT_INFO_RESPONSE_REQUESTED, ContactInfoSucceeded, ContactInfoFailed ,
CONTACT_INFO_SELECTION_RESPONSE_REQUESTED, ContactInfoSelectionSucceeded,
ContactInfoSelectionFailed,
ContactInfoServiceResponse
} from '../actions/actions';
import { mergeMap, map, catchError, delay } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { of } from 'rxjs';
@Injectable()
export class ContactInfoEffect {
@Effect()
fetchContactInfoResponse = this.actions.pipe(
ofType(CONTACT_INFO_RESPONSE_REQUESTED),
delay(250),
mergeMap((action) =>
this.contactTriageService.getContentInfo().
pipe(map((contacts) => new ContactInfoSucceeded(contacts)),
catchError(() => of(new ContactInfoFailed()))
),
)
)
constructor(
private actions: Actions,
private contactTriageService: ContactTriageService
) { }
}
// effects.spec.ts
import { TestBed } from '@angular/core/testing';
import { of, ReplaySubject, Subject, EMPTY } from 'rxjs';
import { StoreModule } from '@ngrx/store';
import { provideMockActions } from '@ngrx/effects/testing';
import { ContactInfoEffect } from './effects';
import { ContactTriageService } from '../views/contact-triage/contact-triage.service';
import { reducers } from '../reducers/reducers';
import { ContactInfoSucceeded } from '../actions/actions';
import { getContactInfoMock } from 'src/server/test/mocks';
import { ContactInfoResponse } from 'src/server/contact-info/interfaces/contact-info.interface';
describe('ContactInfoEffect', () => {
let effects: ContactInfoEffect;
let contactTriageService: ContactTriageService;
let actions: Subject<any>;
beforeEach(async () => {
TestBed.configureTestingModule({
imports: [StoreModule.forRoot(reducers)],
providers: [
ContactInfoEffect,
{
provide: ContactTriageService,
useValue: {
getContentInfo() {
return EMPTY;
}
}
},
provideMockActions(() => actions)
]
});
effects = TestBed.get(ContactInfoEffect);
contactTriageService = TestBed.get(ContactTriageService);
});
it('should dispatch `ContactInfoSucceeded` if the service returns successfully', () => {
const response:ContactInfoResponse = getContactInfoMock();
const contactTriageServiceSpy = spyOn(
contactTriageService,
'getContentInfo'
).and.returnValue(of( [
getContactInfoMock()
]));
actions = new ReplaySubject(1);
actions.next(new ContactInfoSucceeded(getContactInfoMock()));
effects.fetchContactInfoResponse.subscribe((result) => {
expect(result).toEqual(new ContactInfoSucceeded(response));
});
});
});
【问题讨论】:
标签: angular unit-testing jasmine ngrx ngrx-effects