‘alert’ is not a known element の対処法
2020年2月7日
テストしたいけど、以下のようなコードが入っているとテストでタイトルのようなエラーになるかと思います。
alert('アラートだよ!');
そんな時は、テストコードに以下を追加すればOKです。
NO_ERRORS_SCHEMA
追加した結果のコードは以下の通りになります。
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core'; // インポートして
import { SampleComponent } from './sample.component';
describe('SampleComponent', () => {
let component: SampleComponent;
let fixture: ComponentFixture<SampleComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SampleComponent ],
schemas: [NO_ERRORS_SCHEMA] // ここに追加する
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
- なんでこれがエラーになるのかというと、aleartなんてAngularの機能じゃないし宣言されてないから知らないよーってことみたいですね。 NO_ERRORS_SCHEMAって書いておけば無視してくれるようになります。
- でもそんな対処方法じゃなんか気持ち悪い。。。と思ったら以下のような形でaleartをimportしてあげれば問題ないです。
※ngx-bootstrapのaleartを利用している場合
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AlertModule } from 'ngx-bootstrap/alert'; // ここでインポートして
import { LoginComponent } from './login.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
imports: [AlertModule.forRoot()] // ここに追加する
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
ちゃんと明示してあげればテスト通るかと思います。
関連