更新模拟对象会给出未定义的错误



我正在使用 Angular 中的 Jasmine 运行我的测试。我需要在运行测试之前更新模拟对象的值。有问题的模拟对象是这里的模拟路由。 正如您在下面的代码中看到的,它当前设置为

let mockRoute = { params: of({ id: '123', type: 'test' }), snapshot: {} };

我需要将其更新为

this.mockRoute = { params: of({ id: '123', type: 'BankAccountCompliance' }), snapshot: {} };

如果你看到我的测试标记为适合,上面有那行代码。不幸的是我收到错误

Cannot set property 'mockRoute' of undefined

如何更新该模拟路由?

测试组件

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);
});

});

我已经解决了。 我所要做的就是

mockRoute.params = of({ id: '123', type: 'BankAccountCompliance'});

最新更新