【问题标题】:How to test the existence of a route in Angular using Jasmine?如何使用 Jasmine 测试 Angular 中路由的存在?
【发布时间】:2020-01-02 21:15:16
【问题描述】:

我正在尝试编写一个测试来检查是否存在使用 Jasmine for Angular 应用程序的路由:

import { routes } from './app-routing.module';
import { UsersComponent } from './users/users.component';

describe('routes', () => {
    it('should contain route for /users', () => {
        const expectedRoute = { path: 'users', component: UsersComponent };
        expect(routes).toContain(expectedRoute);
    });
});

但测试失败(可能是因为 Javascript How object equality checks work in Javascript? 中的对象相等)

如何修改测试以使其工作?

【问题讨论】:

  • 我不会在单元测试中测试这个。如果整个页面都丢失了,您应该很快从 E2E 测试中找出答案。
  • 单元测试很快,当路由名称拼写错误或路由指向的组件不是预期的组件时,它们会指出来。我知道维护这样的测试会因为它改变的可能性而变得更加困难,但在我的情况下这是值得的。
  • 他们会,但这只是变更检测。也许你想改变路由或者组件,现在你每次都要改变单元测试。 是什么 路线并不重要,重要的是其他组件是否导航到正确的位置,这个单元测试无法告诉你。这就是为什么我认为在其他级别上进行更好的测试。
  • 我想我喜欢同时拥有变化检测快速单元测试和检测路由错误配置的 e2e 测试的想法。

标签: angular unit-testing jasmine integration-testing angular2-routing


【解决方案1】:

我已经尝试过了,它适用于您的代码。

方法toContain中的相等没有问题。

您是否将app-routing.module.ts 中的const routes 更改为export const routes,并在您的测试中将import { routes } from './app-routing.module' 更改为import { routes } from './app-routing.module'?

这是我为了测试应用程序而必须更改的唯一内容。

我做了以下步骤:

  • ng new test-routing(对路由说“是”,因此创建了 app-routing.module.ts。
  • 用以下代码修改app.component.spec.ts:
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

import { routes } from './app-routing.module';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should contain route for /principal', () => {
        const expectedRoute = { path: 'principal', component: AppComponent };
        expect(routes).toContain(expectedRoute);
  });
});
  • 修改app-routing.module.ts 以添加此路由:
export const routes: Routes = [
  { path: '', redirectTo: '/principal', pathMatch: 'full' },
  { path: 'principal', component: AppComponent }
];
  • 运行ng test

测试很好。

如果我将'principal' 路径更改为其他路径,则测试失败。 如果我恢复到好的,测试就可以了。

【讨论】:

  • 按照您的步骤从头开始,它可以工作;在我的应用程序中它没有,所以我认为它与模块边界有关。我将 routes 数组移动到测试而不是导入它;它立即发挥了如此明显的作用,这不是我最初假设的平等。您可能不需要在测试台中配置模块,因为它是一个简单的单元测试。我会接受答案。
  • 对此的跟进,对于新的 Ivy 编译器至关重要的提前编译“aot”导致了奇怪的行为,我不确定它现在是否在最新版本中得到修复但是这样的事情因此失败了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 2015-06-15
  • 1970-01-01
相关资源
最近更新 更多