Angular 2 & Jasmine: Error: Please call "TestBed.compileComponents" before starting the test.

I get this error:

Error: This test module uses the component MessagesComponent which is using a "templateUrl", but they were never compiled. Please call "TestBed.compileComponents" before your test. 

When trying to run this simple Angular 2 test and Jasmine test:

  let comp: MessagesComponent; let fixture: ComponentFixture<MessagesComponent>; describe('MessagesComponent', () => { beforeEach(() => { TestBed.configureTestingModule({ declarations: [ MessagesComponent ], providers: [ {provide: DataService, useValue: {} } ] }) .compileComponents(); // compile template and css fixture = TestBed.createComponent(MessagesComponent); comp = fixture.componentInstance; }); it('example', () => { expect("true").toEqual("true"); }); }); 

I think this may be due to my test web package configuration:

 'use strict'; const path = require('path'); const webpack = require('webpack'); module.exports = { devtool: 'inline-source-map', module: { loaders: [ { loader: 'raw', test: /\.(css|html)$/ }, { exclude: /node_modules/, loader: 'ts', test: /\.ts$/ } ] }, resolve: { extensions: ['', '.js', '.ts'], modulesDirectories: ['node_modules'], root: path.resolve('.', 'src') }, tslint: { emitErrors: true } }; 
+8
source share
2 answers

Template sampling is asynchronous when your templates are not built into your components, so you need to tell Jasmine about it. The change

 beforeEach(() => { TestBed.configureTestingModule({ ... }) .compileComponents(); fixture = TestBed.createComponent(MessagesComponent); comp = fixture.componentInstance; }); 

to

 beforeEach(async(() => { TestBed.configureTestingModule({ ... }) .compileComponents() .then(() => { fixture = TestBed.createComponent(MessagesComponent); comp = fixture.componentInstance; }); })); 
+17
source

Since you are already using webpack , theoretically you would not need to call the compileComponents() function in accordance with the webpack paper here , since webpack builds templates and css as part of the automatic build process that precedes running the test.

One of the possible reasons your template / css is not embedded is the IDE ( VisualStudio/WebStorm/IntelliJ ), which automatically compiles your ts to js, ​​and the webpack loaders that target js/ts files try to apply to already compiled js files instead of the original ts files.

0
source

Source: https://habr.com/ru/post/1012049/


All Articles