gpt4 book ai didi

javascript - Angular 单元测试 : Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL 段: 'logout'

转载 作者:行者123 更新时间:2023-12-01 01:08:59 29 4
gpt4 key购买 nike

当我启用 login.spec.ts 测试时,对于不同的测试,我总是随机收到此错误。未捕获错误:未捕获( promise ):错误:无法匹配任何路由。 URL 段:“注销”

我尝试使用以下方法伪造 authService 中的注销方法:spyOn(authService, '注销').and.returnValues(true);但还是不行。请帮助解决这里的问题。

登录.component.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']);
}
}

现在是我的

登录.组件.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 部分,但我认为在 onInit 调用 logout 函数不是正确的实现。

imports: [
RouterTestingModule.withRoutes([
{ path: 'logout', component: LogoutComponent }
]),
HttpClientTestingModule
]

请告诉我这是否有效,我们会从中找出答案。我认为即使这解决了您的问题,它也很难测试您的测试用例。

关于javascript - Angular 单元测试 : Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL 段: 'logout',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55336064/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com