如何在运行测试时按模块修复意外的组件声明?

时间:2019-06-19 09:09:18

标签: angular jestjs

我正在尝试对具有两个组件的我的角度应用程序执行单元测试。根AppComponent和一个myFormComponent。我想对myFormComponent中可用的表单字段执行单元测试。

我已经仔细阅读了此处提供的所有答案,但似乎没有一个对我有用。提供的答案是针对运行应用程序时遇到的问题,但我的问题是当我使用“ npm run test”运行测试时。

// app.module.ts

  import { BrowserModule } from "@angular/platform-browser";
    import { NgModule } from "@angular/core";

    import { AppComponent } from "./app.component";
    import { MyFormComponent } from "./my-form/my-form.component";
    import { FormsModule, ReactiveFormsModule } from "@angular/forms";

    @NgModule({
    declarations: [AppComponent, MyFormComponent],
    imports: [BrowserModule, FormsModule, ReactiveFormsModule],
    providers: [],
    bootstrap: [AppComponent]
    })
    export class AppModule {}

// my-form.component.spec.ts

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

    import { MyFormComponent } from "./my-form.component";
    import { DebugElement } from "@angular/core";
    import { By } from "@angular/platform-browser";
    import { AppComponent } from "../app.component";

    describe("MyFormComponent", () => {
    let component: MyFormComponent;
    let fixture: ComponentFixture<MyFormComponent>;

    let debugElement: DebugElement;
    let htmlElement: HTMLElement;

    beforeEach(async(() => {
    TestBed.configureTestingModule({
    declarations: [MyFormComponent]
    }).compileComponents();
    }));

    beforeEach(() => {
    fixture = TestBed.createComponent(MyFormComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();

    // debugElement = fixture.debugElement.query(By.css("p"));
    // htmlElement = debugElement.nativeElement;
    });

    test("check dummy", () => {
    const res = 2 * 3;
    expect(res).toBe(6);
  });
});

实际上,该测试用例应该通过,但是没有通过。我收到错误消息“模块'DynamicTestModule'声明了意外的值'MyFormComponent'。请添加@ Pipe / @ Directive / @ Component批注。”。当我删除第一个“ beforeEach”方法时,它似乎可以工作。

0 个答案:

没有答案