我刚接触测试。有一个功能,当它被调用时,导航到一个新的页面。但测试失败并出现错误:
预期的间谍导航已被调用[[ ' ./../管理/文件/ 12345' ]]但它从未被召唤过。
public showProfile(id) {
this.router.navigate(['./../admin/documents/' + id]);
}
在我的测试文件中,我有:
import {ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { AppComponent} from './app.component';
import {FormsModule} from "@angular/forms";
import {HttpClientTestingModule} from "@angular/common/http/testing";
import {Router} from "@angular/router";
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let mockRouter;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent],
imports: [FormsModule, HttpClientTestingModule],
providers: [
{ provide: Router, useValue: mockRouter }]
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
mockRouter = {
navigate: jasmine.createSpy('navigate')
};
});
describe('when showProfile() is called', () => {
it('navigates to a profile page',() => {
const id= 12345;
component.showProfile(id);
expect(mockRouter.navigate)
.toHaveBeenCalledWith(['./../admin/documents/' + id]);
});
});
});
答案 0 :(得分:1)
在mockRouter
中使用TestBed.configureTestingModule
之前,您需要初始化expect(mockRouter.navigate).toHaveBeenCalledWith(['./../admin/documents/' + id]);
。
此外,['a'] !== ['a']
因expect(mockRouter.navigate.calls.mostRecent().args[0][0])
.toEqual('./../admin/documents/' + id);
而无法工作。作为一种解决方法,您可以执行以下操作:
-vm
C:/Program Files/Java/jdk1.8.0_131/bin/javaw.exe
我为您的测试创建了Stackblitz。