ふらぱいく

備忘録。いい加減つける

Angular で ComponentファイルをRenameしたときに怒られたのでメモ

環境

  • Angular CLI: 8.0.1
  • Node: 12.3.1
  • WebStorm: 2019.1.02

怒られた

Angular入門してみる_6 でAppComponent を Members.Component.ts にリネームした際,以下のようなエラーが出た。

src/app/app.component.spec.ts(1,10): error TS2305: Module '"G:/noinoi/Documents/Angular_study/04-6/src/app/app.com
ponent"' has no exported member 'MembersComponent'.

コンポーネントを見つけられなかった?

原因?

app.component.ts を作成したときに同時に作成される app.component.spec.ts に注目。
memebers.component.ts にリネームした際に,コード内のコンポーネント名だけリネームされて,ファイル名はapp.component.spec.tsのまま残っていたのが原因?

import { MembersComponent } from './app.component';

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By }           from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

describe('MembersComponent', function () {
  let de: DebugElement;
  let comp: MembersComponent;
  let fixture: ComponentFixture<MembersComponent>;

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

  beforeEach(() => {
    fixture = TestBed.createComponent(MembersComponent);
    comp = fixture.componentInstance;
    de = fixture.debugElement.query(By.css('h1'));
  });

  it('should create component', () => expect(comp).toBeDefined() );

  it('should have expected <h1> text', () => {
    fixture.detectChanges();
    const h1 = de.nativeElement;
    expect(h1.innerText).toMatch(/angular/i,
      '<h1> should say something about "Angular"');
  });
});

解決方法

MembersComponent を すべて AppComponentにリファクタリング

import { AppComponent } from './app.component';

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By }           from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

describe('AppComponent', function () {
  let de: DebugElement;
  let comp: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

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

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.componentInstance;
    de = fixture.debugElement.query(By.css('h1'));
  });

  it('should create component', () => expect(comp).toBeDefined() );

  it('should have expected <h1> text', () => {
    fixture.detectChanges();
    const h1 = de.nativeElement;
    expect(h1.innerText).toMatch(/angular/i,
      '<h1> should say something about "Angular"');
  });
});

なおった。
ちなみに「~.spec.ts」はテストクラスのファイルだそうです。