我正在使用Angular中的Jasmine进行测试。在运行测试之前,我需要更新模拟对象的值。有问题的模拟对象是此处的mockRoute。 正如您在下面的代码中看到的那样,它当前设置为
let mockRoute = { params: of({ id: '123', type: 'test' }), snapshot: {} };
我需要将其更新为
this.mockRoute = { params: of({ id: '123', type: 'BankAccountCompliance' }), snapshot: {} };
如果您看到我的测试标记为“适合”,则上面有这行代码。不幸的是我遇到错误
Cannot set property 'mockRoute' of undefined
如何更新该模拟路由?
TestComponent
describe('ApproveComponent', () => {
let component: ApproveComponent;
let injector: TestBed;
let fixture: ComponentFixture<ApproveComponent>;
const mockService: ApprovalsService = <ApprovalsService>{
approve: (id: string, type: string, message: string) => <Promise<any>>{},
reset: (id: string, type: string, message: string) => <Promise<any>>{},
reject: (id: string, type: string, message: string) => <Promise<any>>{},
get: (type: string, id: string) => <Promise<any>>{},
};
let mockRoute = { params: of({ id: '123', type: 'test' }), snapshot: {} };
function setupComponent(getResult: any = {}) {
spyOn(mockService, nameof<ApprovalsService>('approve')).and.returnValue(Promise.resolve({}));
spyOn(mockService, nameof<ApprovalsService>('reset')).and.returnValue(Promise.resolve({}));
spyOn(mockService, nameof<ApprovalsService>('reject')).and.returnValue(Promise.resolve({}));
spyOn(mockService, nameof<ApprovalsService>('get')).and.returnValue(Promise.resolve(getResult));
TestBed.configureTestingModule({
imports: [
DxTextAreaModule,
DxButtonModule,
SharedModule,
RouterTestingModule.withRoutes([{ path: 'approvals', component: ApproveComponent }])
],
declarations: [ApproveComponent],
providers: [
{ provide: ApprovalsService, useValue: mockService },
{ provide: ActivatedRoute, useValue: mockRoute },
{ provide: MessageService, useClass: MockMessageService },
{ provide: ConfirmationDialogService, useValue: ConfirmationDialogServiceMock },
{ provide: NgxPermissionsService, useClass: MockNgxPermissionsService }
]
})
.compileComponents();
fixture = TestBed.createComponent(ApproveComponent);
injector = getTestBed();
component = fixture.componentInstance;
spyOn((<any>component).router, 'navigate').and.returnValue(true);
fixture.detectChanges();
}
it('should create and call get', () => {
setupComponent();
expect(component).toBeTruthy();
expect(mockService.get).toHaveBeenCalled();
});
fit('should hide the Reset button when type is BankAccount', () => {
this.mockRoute = { params: of({ id: '123', type: 'BankAccountCompliance' }), snapshot: {} };
setupComponent();
// component.isBankAccount = false;
// component.type = 'BankAccountCompliance';
// fixture.detectChanges();
expect(component.isBankAccount).toBe(true);
});
it('should show the Reset button when type is BankAccount', () => {
setupComponent();
// component.isBankAccount = false;
// component.type = 'IbaCompliance';
// fixture.detectChanges();
expect(component.isBankAccount).toBe(false);
});
});
答案 0 :(得分:0)
我解决了。我要做的就是
mockRoute.params = of({ id: '123', type: 'BankAccountCompliance'});