angular - 在 Angular Testing 中注入(inject)位置

标签 angular testing karma-runner

我在我的 Angular 组件中使用 Location 注入(inject)来将用户重定向到另一条路线。它按预期工作,但当我运行测试时,我收到此消息

Error: StaticInjectorError(DynamicTestModule)[CreateGroupComponent -> Location]: StaticInjectorError(Platform: core)[CreateGroupComponent -> Location]: NullInjectorError: No provider for Location!

这是我的测试类

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { CreateGroupComponent } from './create-group.component';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { GroupService } from '../core/groupService/group.service';
import { AuthService } from '../core/authService/auth.service';
import { RouterTestingModule } from '@angular/router/testing';

describe('CreateGroupComponent', () => {
  let component: CreateGroupComponent;
  let fixture: ComponentFixture<CreateGroupComponent>;

  beforeEach(async(() => {

    const mockGroupService: any = {

    };

    const mockAuthService: any = {

    };

    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule],
      declarations: [CreateGroupComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [{ provide: AuthService, useValue: mockAuthService }, { provide: GroupService, useValue: mockGroupService }]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CreateGroupComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

最佳答案

我承认,我也在学习 Angular 测试,但是...您不需要将“RouterTestingModule”添加到您的 TestBed 的“imports:[]”数组吗?

imports: [RouterTestingModule, ReactiveFormsModule],

关于angular - 在 Angular Testing 中注入(inject)位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49261066/

相关文章:

angularjs - 单元测试 angular.service ,beforeEach 注入(inject)不执行

javascript - AngularJS Karma 测试中的 jQuery 触发事件

typescript /karma : Making CommonJS available to Karma during test runs

python - 在 else 中捕获异常

testing - 在 hudson 中设置测试构建作业,检测 make 何时无法编译

angular - 引用错误 : window is not defined SSR ANGULAR

html - 在 Angular Material 中隐藏来自 mat-form-field 的箭头

angular - fa 图标不随 ngClass 变化

angular - 当以 5/6 Angular Angular 单击按钮时,如何从 url 下载文件

testing - 有没有办法在一个人的测试类之外使用 TestNG DataProvider?