我正在努力让我的测试适用于我的路线的CanLoad
方法。
这是我想测试的代码:
@Injectable()
export class ContractGuard implements CanLoad {
constructor(private router: Router, private contractService: ContractService) { }
public canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
return this.contractService.getContracts().map((contracts: Array<Contract>) => {
// My test does not hit this spot
if (contracts) {
this.router.navigate([contracts[0].id, "Home"]);
return true;
}
return false;
}).catch(() => {
return Observable.of(false);
});
}
}
我已经使用MockBackend
创建了一个模拟并运行了测试,但.map
的{{1}}未被调用。
这是测试设置:
getContracts()
如何让describe("ContractGuard", () => {
let contractGuard: ContractGuard;
let contractService: ContractService;
let router: Router;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ContractService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
deps: [MockBackend, BaseRequestOptions],
useFactory: (backend: XHRBackend, defaultOptions: BaseRequestOptions) => new Http(backend, defaultOptions)
}
]
});
let contracts = Array<Contract>();
contracts.push(new Contract());
contracts.push(new Contract());
router = TestBed.get(Router);
contractService = TestBed.get(ContractService);
let backend = TestBed.get(MockBackend);
backend.connections.subscribe((connection: MockConnection) => {
connection.mockRespond(new Response(new ResponseOptions({ body: contracts })));
});
});
// TODO: To be continued
xit("should load app route", () => {
// Arrange
// Act
// Assert
});
});
被召唤?
修改
我完成了测试,但.map
仍未被调用:
map
修改
好的,我不会将此作为答案发布,因为IMO这不是解决问题的最佳方法。我正在订阅describe("ContractGuard", () => {
let contractGuard: ContractGuard;
let contractService: ContractService;
let router = {
navigate: jasmine.createSpy("navigate")
};
beforeEach(() => {
let contracts = Array<Contract>();
contracts.push(new Contract(1, 1, "KWK 1"));
contracts.push(new Contract(2, 1, "KWK 2"));
TestBed.configureTestingModule({
providers: [
{ provide: Router, useValue: router },
{ provide: ContractService, useValue: { getContracts: () => { return Observable.of(contracts); } } },
MockBackend,
BaseRequestOptions,
{
provide: Http,
deps: [MockBackend, BaseRequestOptions],
useFactory: (backend: XHRBackend, defaultOptions: BaseRequestOptions) => new Http(backend, defaultOptions)
}
]
});
router = TestBed.get(Router);
contractService = TestBed.get(ContractService);
let backend = TestBed.get(MockBackend);
backend.connections.subscribe((connection: MockConnection) => {
connection.mockRespond(new Response(new ResponseOptions({ body: contracts })));
});
});
it("should load app route", () => {
// Arrange
let guard = new ContractGuard(<any>router, contractService);
// Act
guard.canLoad(null);
// Assert
contractService.getContracts().subscribe((contracts) => {
expect(router.navigate).toHaveBeenCalled(); // False
expect(contracts.length).toBe(2); // True
});
});
});
,但我希望,路由器应对此负责。
这是解决方法:
canLoad