javascript - 角度单元测试:未捕获错误:未捕获(承诺):错误:无法匹配任何路由。URL 段:“注销”
问题描述
当我启用 login.spec.ts 测试时,我总是在不同的测试中随机出现此错误。 未捕获的错误:未捕获(承诺):错误:无法匹配任何路由。URL 段:“注销”
我尝试使用以下方法伪造 authService 中的注销方法: spyOn(authService, 'logout').and.returnValues(true); 但它仍然不起作用。请帮助解决这里的问题。
登录组件.ts
export class LoginComponent implements OnInit {
isLoggingIn = false;
constructor(
private authService: AuthService
) { }
ngOnInit() {
this.authService.logout();
}
}
authService.ts
@Injectable()
export class AuthService {
public userSource: BehaviorSubject<string | undefined> = new BehaviorSubject<string | undefined>(undefined);
constructor(
private myRoute: Router) {
}
logout() { // TODO: Right now this is fake logout. We need to either destroy express session or cookie.
this.userSource.next(undefined);
this.myRoute.navigate(['logout']);
}
}
现在我的
login.component.spec.ts
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
providers: [ AuthService,
ConfigService
],
imports: [ RouterTestingModule,
HttpClientTestingModule ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
解决方案
你有一个错误,因为即使你在RouterTestingModule
这里使用过,你也没有配置路由。如下配置您imports
的规范部分,但我认为调用logout
函数不是onInit
正确的实现。
imports: [
RouterTestingModule.withRoutes([
{ path: 'logout', component: LogoutComponent }
]),
HttpClientTestingModule
]
告诉我这是否有效,我们会从那里弄清楚。我认为即使这可以解决您的问题,它也很难测试您的测试用例。
推荐阅读
- python - Python:检查、比较时间、日期。验证日期
- javascript - 从 Jest 中的函数中清除值
- android - 两个日期的查询之间的领域不起作用
- php - 从 sqlite 数据库中选择查询时如何绑定?
- bash - 在 Mac 终端中使用 for 循环打印每个文件名的字符数
- python - Python将字符串转换为日期时间以查找差异
- javascript - JS:加载的 json 未定义,即使它不是
- reporting-services - 不根据 IF 更改 Tablix rdlc 中的字体或单元格颜色 - 改为更改文本
- sql - 如何在 Sql Server 中以原子方式更新复合对象?
- sql - SQL 查询在 DBeaver 中有效,但在 Oracle Apex 中无效