Angular:单元测试路由:预期“”为“/route”

2023-12-27

我正在对我的 Angular 应用程序下的路由进行单元测试,

我的路线在 app.module.ts 下导入的特定模块中声明,

这是我的路由模块:

应用程序路由.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { LoginComponent } from './login/login.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { CustomersListComponent } from './customer/customers-list/customers-list.component';
import { CustomerDetailComponent } from './customer/customer-detail/customer-detail.component';
import { ApplicationParametersComponent } from './superAdministrator/application-parameters/application-parameters.component';
import { InscriptionComponent } from './inscription/inscription.component';

const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: 'login',  component: LoginComponent },
  { path: 'login/:keyWording',  component: LoginComponent },
  { path: 'welcome', component: WelcomeComponent },
  { path: 'customers-list', component: CustomersListComponent },
  { path: 'customer-create', component: CustomerDetailComponent },
  { path: 'customer-detail/:idCustomer', component: CustomerDetailComponent },
  { path: 'application-parameters', component: ApplicationParametersComponent },
  { path: 'inscription', component: InscriptionComponent }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

这是我的 app.module.ts (用于导入路由模块:

import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { SharedModule } from './../shared/shared.module';
import { LoginComponent } from './login/login.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { AppComponent } from './app.component';
import { CustomerModule } from './customer/customer.module';
import { ApplicationParametersComponent } from './superAdministrator/application-parameters/application-parameters.component';
import { InscriptionComponent } from './inscription/inscription.component';

import { DxProgressBarModule } from 'devextreme-angular';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    WelcomeComponent,
    ApplicationParametersComponent,
    InscriptionComponent
  ],
  imports: [
    AppRoutingModule, /* HERE IS THE ROUTING FILE */

    SharedModule,
    CustomerModule,
    DxProgressBarModule/*,
    BrowserAnimationsModule,
    BrowserModule*/
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

在我的测试文件下,我遵循了此博客中的教程:https://codecraft.tv/courses/angular/unit-testing/routing/ https://codecraft.tv/courses/angular/unit-testing/routing/

我的路由测试的测试文件如下:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
// DevExtreme Module
import {DxProgressBarModule, DxTemplateModule} from 'devextreme-angular';
// Router Modules
import {RouterTestingModule} from '@angular/router/testing';
// Services and HTTP Module
import { SessionService } from './../shared/service';
import { HttpService } from './../shared/service';
import {HttpModule} from '@angular/http';
// Routs testing
import {Router, RouterModule} from '@angular/router';
import {fakeAsync, tick} from '@angular/core/testing';
import {Location} from '@angular/common';
import {LoginComponent} from './login/login.component';
import {WelcomeComponent} from './welcome/welcome.component';
import {ApplicationParametersComponent} from './superAdministrator/application-parameters/application-parameters.component';
import {InscriptionComponent} from './inscription/inscription.component';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {FormsModule} from '@angular/forms';


describe('Testing the application routes', () => {

  let location: Location;
  let router: Router;
  let fixture;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, FormsModule , DxTemplateModule , HttpModule ],
      providers:    [SessionService , HttpService ],
      declarations: [
        AppComponent,
        LoginComponent,
        WelcomeComponent,
        ApplicationParametersComponent,
        InscriptionComponent
      ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]

    });

    router = TestBed.get(Router);
    location = TestBed.get(Location);

    fixture = TestBed.createComponent(AppComponent);
    router.initialNavigation();
  });

  it('navigate to "inscription" takes you to /inscription', fakeAsync(() => {
    router.navigate(['inscription']);
    tick();
    expect(location.path()).toBe('/inscription');
  }));
});

我的测试失败,表明这一点:

Expected '' to be '/inscription'.
    at Object.<anonymous> (webpack:///src/app/app-routing.spec.ts:52:28 <- src/test.ts:143891:33)
    at Object.<anonymous> (webpack:///~/@angular/core/@angular/core/testing.es5.js:348:0 <- src/test.ts:34691:26)
    at ZoneDelegate.invoke (webpack:///~/zone.js/dist/zone.js:391:0 <- src/polyfills.ts:1546:26)
    at ProxyZoneSpec.Array.concat.ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- src/test.ts:232357:39)

Ideas ??


您忘记导入路由到RouterTestingModule,在您的测试文件中。

你必须添加export关键字到您的const routes在你的AppRoutingModule文件,然后你可以import测试文件中的路由(并将它们添加到测试配置中)。

import {routes} from '...'; // I don't have the app-routing.module file path.
...
...
...
 beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes(routes), <-- I added the routes here.
                FormsModule , DxTemplateModule , HttpModule 
  ],
      providers:    [SessionService , HttpService ],
      declarations: [
        AppComponent,
        LoginComponent,
        WelcomeComponent,
        ApplicationParametersComponent,
        InscriptionComponent
      ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]

    });

    router = TestBed.get(Router);
    location = TestBed.get(Location);

    fixture = TestBed.createComponent(AppComponent);
    router.initialNavigation();
  });

如果你没有在路由器测试模块中加载路由,那么当你访问路由器时,它就无法知道要去哪里。navigate,因此它将返回到原始页面,并在控制台中出现错误。

您遵循的教程有一种非常奇怪的方式来处理路由,因为tick()是用来fakeAsync测试,这是一个真实的async一。所以你必须使用Promise<boolean>由返回路由器导航 https://angular.io/api/router/Router#navigate:

it('navigate to "inscription" takes you to /inscription', () => {
    router.navigate(['inscription']).then(() => {
        expect(location.path()).toBe('/inscription');
    });
});

如您所见,您还可以删除fakeAsync因为这不是假的,而是async call.

在 plunker 上查看 http://plnkr.co/edit/ZoFQi4NmWT0CF3d9z7BI?p=preview

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular:单元测试路由:预期“”为“/route” 的相关文章

随机推荐

  • 使用垂直分割打开新的 Emacs 缓冲区

    如何在 Emacs 中将垂直分割设置为默认而不是水平分割 My use case I want to compare a Python file with an older revision of itself from the svn r
  • 在 docker buildkit 中使用秘密标志的正确方法

    我正在努力解决加文提到的同样问题这个问题 https stackoverflow com questions 56865849 setting docker env var from build secret 特别是在新docker构建秘密
  • 尝试获取准确的信息(CTE - 递归)

    我有不同的桌子和goal是获取每个客户的批准工作流程 以这种方式显示该信息 gt 客户 批准者1 批准者2 批准者3 批准者4 首先 我有一个名为实体的表 12 Math Andrew 308 CHAIN1 MathAndrew 13 Jo
  • 为什么应该避免在 servlet 中使用 InheritableThreadLocal?

    我在用InheritableThreadLocal in my Servlet班级 这样它就可以从它的子线程中使用 这是邪恶的使用吗InheritableThreadLocal在线程池执行器中 比如servlet线程池 我的问题 1 为什么
  • Three.js - 蒙皮骨架网格物体实例、动画和混合

    我正在开发一款小型多人游戏 该游戏有一个单一皮肤的玩家网格 有许多玩家使用它 一些背景 我尝试通过 Maya 和 Blender Collada 导出加载 两者似乎都引用了某种形式的动画数据 但我无法让它工作 我尝试过 Maya JSON
  • Flutter - 仅在首次加载时无法加载资源

    我在我的 flutter 应用程序上加载图像 如下所示 Image asset imageFilePath fit BoxFit cover 当我第一次在模拟器上运行应用程序时 出现以下异常 I flutter 7194 图像资源服务捕获异
  • 使用 WSE 3.0 添加 SOAP:HEADER 用户名和密码

    我已经成功创建了一个 WS 客户端 该客户端在不使用身份验证时可以正常工作 但是 服务器 WebSphere 现在需要添加 ws security 用户名令牌 而我很难做到这一点 生成的 SOAP 消息应该如下所示
  • 如何将软件版本从 Azure DevOps 部署到内部服务器?

    我们的软件托管在 Azure DevOps 上的 Git 中 并使用构建管道 主要使用 Cake 脚本 进行构建 我们现在希望使用 Azure DevOps 发布管道来部署该软件 然而 我们所有的应用程序服务器都位于防火墙后面 网络内部 除
  • ASP.NET WebPart 和 Google Chrome

    Hi there 这几天开始学习ASP NET Google Chrome 是我的默认浏览器 我也在 Google Chrome 中测试我的应用程序 我发现当我使用 Chrome 时 ASP NET 的某些元素不会实时运行 例如 ASP N
  • 检查对象是否为 Null 或未定义

    我有一个包含可选变量参数的函数 默认情况下 我将变量设置为NULL 但如果不是NULL我希望我的功能可以做一些事情 我需要一种方法来检查变量是否不为空 这很复杂 因为我正在使用 tidyeval 并且只是使用is null var 抛出未找
  • VBA、ADO.Connection 和查询参数

    我有 Excel VBA 脚本 Set c nn CreateObject ADODB Connection conn Open report Set rs conn Execute select from table 脚本工作正常 但我想
  • linux下如何挂载android的img文件? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 最近 我对android rom感兴趣 我想更改和重建它们 所以 我在我的 XOOM 上做了一些测试
  • C++:Cheat Engine 和 ArtMoney 等应用程序如何工作?

    问完后这个问题 C 我可以用指针超出应用程序的内存范围吗 https stackoverflow com questions 2976058 c can i get out of the bounds of my apps memory w
  • 我怎样才能找到这个 Json 对象的长度

    我想找到这个 JSON 对象的长度 所以有人告诉我如何获得 JSON 对象的长度 意味着我想知道这个 json 对象包含多少数据 var ddData 01 United States 02 United Kingdom 03 Aruba
  • 是否有一个函数可以将 ipAddress 作为字符串并告诉我它是否是不可路由的 IP 地址?

    我正在尝试确定 IP 地址是否可路由 例如 如果我收到 127 0 0 1 我就知道这是环回 即 localhost 我无法在 NET 或任何其他语言中找到此功能 因此我开始编写自己的函数 但还远未完成 在我花大量时间编写这个函数之前 有谁
  • 将平铺 Google 地图与 OpenLayers 3 结合使用

    如何将 google 地图与 OpenLayers 3 一起使用 我想从 OpenLayers 2 迁移到 3 这是一个例子 谷歌地图与 OpenLayers 集成示例 http openlayers org en v3 0 0 examp
  • 每天按顺序选择 10 行

    我有一个带有日期 时间戳 记录的数据库 我需要每天选择10条记录 每天还有更多 并按几列对它们进行排序 该查询应该是什么样子 您必须每天在子查询中获取 10 条记录 并通过左连接将它们连接到主表 这样您每天最多可以获得 10 条记录 SQL
  • 错误:“无法修改返回值”c#

    我正在使用自动实现的属性 我想解决以下问题的最快方法是声明我自己的支持变量 public Point Origin get set Origin X 10 fails with CS1612 错误消息 无法修改 表达式 的返回值 因为 它不
  • 在单个查询中从 mongodb 中的 2 个集合中获取数据

    我想从 2 个独立的集合中获取数据并根据date通过单个查询 这甚至可能在mongodb 我有收藏 订单类型1 id 1 name Hello1 date 2016 09 23T15 07 38 000Z id 2 name Hello1
  • Angular:单元测试路由:预期“”为“/route”

    我正在对我的 Angular 应用程序下的路由进行单元测试 我的路线在 app module ts 下导入的特定模块中声明 这是我的路由模块 应用程序路由 module ts import NgModule from angular cor