我正在尝试设置一个StackBlitz与茉莉花测试。我设法添加了一个简单的测试,问题是,通过这样做,我打破了我的路由。只要我点击其中一个按钮,我就会得到一个错误:
Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'login'
我相信这与main.ts
文件有关。也许我应该在某个地方初始化我的AppModule
(或AppRoutingModule
?),因为这是路由定义的地方。但我不知道怎么做。
正如您在main.ts
中看到的,我注释掉了旧代码。但每次我尝试添加它的片段,我得到这个错误:
Error in /turbo_modules/@angular/core@11.2.0/__ivy_ngcc__/bundles/core.umd.js (29742:19) A platform with a different configuration has been created. Please destroy it first.
编辑:我已经修复了Alif50解释的第一个错误,但是路由仍然不工作。这是我更新的StackBlitz。
EDIT2:作为参考,这是我在添加测试之前的原始应用程序。如您所见,我可以在两个页面之间导航。一旦Karma运行,就没有办法保持这个功能了吗?我似乎一次只能设置一个组件,一个有测试运行(即,如果我写一个测试LoginComponent,那么我将看到该组件而不是HeaderComponent…我希望我的原始应用程序像它一样运行,最重要的是让我的测试运行)
如果你想在RouterTestingModule
中点击它们,你需要注册路由。
import { Component } from "@angular/core";
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { RouterTestingModule } from "@angular/router/testing";
import { HeaderComponent } from "./header.component";
@Component({})
class DummyComponent {} // Create a dummy component for router config
describe("HeaderComponent", () => {
let component: HeaderComponent;
let fixture: ComponentFixture<HeaderComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [HeaderComponent],
imports: [
RouterTestingModule.withRoutes([
{ path: "login", component: DummyComponent },
{ path: "activities", component: DummyComponent } // register the routes
])
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it("should create", () => {
expect(component).toBeTruthy();
});
it("should work", () => { // this test should work now after doing the above
const login = fixture.debugElement.query(By.css("button")).nativeElement;
login.click();
// ... your other expects
});
});