StackBlitz:将 jasmine-tests 添加到具有路由的应用程序

问题描述

我正在尝试使用 jasmine 测试设置 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: 作为参考,这是我添加测试之前的 original application。如您所见,我可以在两个页面之间导航。一旦 Karma 运行,有没有办法保留此功能?我似乎一次只能设置一个组件,一个正在运行测试的组件(即,如果我为 LoginComponent 编写测试,那么我将看到 HeaderComponent 的组件 INSTEAD ......我想要我原来的应用程序像以前一样运行,最重要的是让我的测试运行)

解决方法

如果您要在 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
  });
});

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...