gpt4 book ai didi

angular - 如何为包含带 Angular 路由器的组件设置测试?

转载 作者:行者123 更新时间:2023-11-28 20:51:42 25 4
gpt4 key购买 nike

我有一个使用 angular(typescript) 构建的应用程序,我正在尝试为 app.component 设置一个测试。该组件中有一个路由器 socket 。我想知道如何在这种情况下正确设置测试。

app.component.spec.ts 看起来像这样

import { TestBed, async } from '@angular/core/testing';
import { inject } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { Component, OnInit, Injectable } from '@angular/core';
import { Router, RouterOutlet } from "@angular/router";
import {DriftInfoDisplayComponent} from "./components/drift-info-display/drift-info-display.component";
import {DriftInfoService} from "./services/http-services/drift-info.service";
import {DriftInfo} from "./model/DriftInfo";

describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
DriftInfoDisplayComponent
],
providers:[
DriftInfoService,
Router,
RouterOutlet
]
}).compileComponents();
}));

it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));

it(`should have as title 'app works!'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app works!');
}));

it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('app works!');
}));
});

但是我在运行 ng test 时失败了

AppComponent should create the app Failed: Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?, ?).

最佳答案

Router 是一个服务,而不是一个模块。这意味着它具有启动和正常工作的依赖项,错误消息告诉您缺少这些依赖项。

您应该从 providers 数组中删除 Router 并将 RouterModule 添加到测试模块中的 import 中。

关于angular - 如何为包含带 Angular 路由器的组件设置测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44049684/

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