I'm trying to do a bare minimum test on my Angular 4 components, and I can't get it to work at all.
I'm running this command: karma start src/test/javascript/karma.conf.js
And here is the output: Error: This test module uses the component AppComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test.
Here is my app.component.spec.ts file:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {AppComponent} from "../../../../../main/webapp/app/admin/app";
describe('AppComponent (minimal)', () => {
it('should create', () => {
TestBed.configureTestingModule({
declarations: [ AppComponent ]
})
.compileComponents();
const fixture = TestBed.createComponent(AppComponent);
const component = fixture.componentInstance;
expect(component).toBeDefined();
});
});
And I just want to test out some of the functions I created in that app.component.ts file, and maybe test some of the HTTML in app.component.html
And here is my karma.conf.js file:
const webpackConfig = require('../../../webpack/webpack.test.js');
const ChromiumRevision = require('puppeteer/package.json').puppeteer.chromium_revision;
const Downloader = require('puppeteer/utils/ChromiumDownloader');
const revisionInfo = Downloader.revisionInfo(Downloader.currentPlatform(), ChromiumRevision);
process.env.CHROMIUM_BIN = revisionInfo.executablePath;
const WATCH = process.argv.indexOf('--watch') > -1;
module.exports = (config) => {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'intl-shim'],
// plugins
plugins: [
require('karma-jasmine'),
require('karma-junit-reporter'),
require('karma-notify-reporter'),
require('karma-chrome-launcher'),
require('karma-remap-istanbul'),
require('karma-sonarqube-reporter'),
require('karma-webpack'),
require('karma-sourcemap-loader'),
require("karma-intl-shim")
],
// list of files / patterns to load in the browser
files: [
'spec/entry.ts'
],
// list of files to exclude
exclude: ['e2e/**'],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'spec/entry.ts': ['webpack', 'sourcemap']
},
webpack: webpackConfig(WATCH),
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots', 'junit', 'progress', 'karma-remap-istanbul', 'notify', 'sonarqube'],
junitReporter: {
outputFile: '../../../../target/test-results/karma/TESTS-results.xml'
},
notifyReporter: {
reportEachFailure: true, // Default: false, will notify on every failed sepc
reportSuccess: true // Default: true, will notify when a suite was successful
},
remapIstanbulReporter: {
reports: { // eslint-disable-line
'lcovonly': 'target/test-results/coverage/report-lcov/lcov.info',
'html': 'target/test-results/coverage',
'text-summary': null
}
},
sonarqubeReporter: {
//basePath: 'src/app', // test files folder
basePath: './', // test files folder
filePattern: '**/*spec.ts', // test files glob pattern
encoding: 'utf-8', // test files encoding
outputFolder: 'target/test-results/karma', // report destination - target/test-results/karma
legacyMode: false, // report for Sonarqube < 6.2 (disabled)
reportName: 'karma-sonarqube-report.xml'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: WATCH,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['ChromiumHeadlessNoSandbox'],
customLaunchers: {
ChromiumHeadlessNoSandbox: {
base: 'ChromiumHeadless',
flags: ['--no-sandbox']
}
},
// Ensure all browsers can run tests written in .ts files
mime: {
'text/x-typescript': ['ts','tsx']
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: !WATCH
});
};
edit: when I try it with this code:
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
I still get the same error, and here is a bit more of my stacktrace:
Error: Uncaught (in promise): Failed to load %3Cdiv%3E%0A%20%20%20%20%3Ch2%3E%0A%20%20%20%20%20%20%20%20%3Cspan%3EApplication%20Management%3C/span%3E%0A%20%20%20%20%20%20%20%20%3Cbutton%.....(lots and lots of "HTML" here)
at resolvePromise (http://localhost:9877webpack:///node_modules/zone.js/dist/zone.js:783:0 <- spec/entry.ts:93156:31)
at resolvePromise (http://localhost:9877webpack:///node_modules/zone.js/dist/zone.js:754:0 <- spec/entry.ts:93127:17)
at http://localhost:9877webpack:///node_modules/zone.js/dist/zone.js:831:0 <- spec/entry.ts:93204:17
at ZoneDelegate.invokeTask (http://localhost:9877webpack:///node_modules/zone.js/dist/zone.js:424:0 <- spec/entry.ts:92797:31)
...
Error: This test module uses the component AppComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test.
at TestBed._initIfNeeded (http://localhost:9877webpack:///node_modules/@angular/core/@angular/core/testing.es5.js:756:0 <- spec/entry.ts:36698:27)
at TestBed.createComponent (http://localhost:9877webpack:///node_modules/@angular/core/@angular/core/testing.es5.js:873:0 <- spec/entry.ts:36815:14)
at Function.TestBed.createComponent (http://localhost:9877webpack:///node_modules/@angular/core/@angular/core/testing.es5.js:652:0 <- spec/entry.ts:36594:29)
at UserContext.<anonymous> (http://localhost:9877webpack:///src/test/javascript/spec/app/admin/app.component.spec.ts:16:26 <- spec/entry.ts:80888:37)
...
Expected undefined to be truthy.
at UserContext.<anonymous> (http://localhost:9877webpack:///src/test/javascript/spec/app/admin/app.component.spec.ts:22:26 <- spec/entry.ts:80893:27)
I do see this talks about my entry.ts, which is here:
TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
declare let require: any;
const testsContext: any = require.context('./', true, /\.spec/);
testsContext.keys().forEach(testsContext);
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { UiTestModule } from '../../../test.module';
import {AccountService, Principal} from "../../../../../../main/webapp/app/shared";
import {DashboardService} from "../../../../../../main/webapp/app/dashboard/dashboard.service";
import {AppService} from "../../../../../../main/webapp/app/admin/app";
import {JhiEventManager, JhiParseLinks} from "ng-jhipster";
import {ActivatedRoute, Router} from "@angular/router";
import {ToasterAlertService} from "../../../../../../main/webapp/app/shared/alert/toaster-alert.service";
import {ToastOptions, ToastsManager} from "ng2-toastr";
import { AppComponent} from "../../../../../../main/webapp/app/admin/app";
import {DomSanitizer} from "@angular/platform-browser";
import {Observable} from "rxjs";
describe('AppComponent', () => {
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
// let service: JhiHealthService;
const fakeActivatedRoute = {
snapshot: { data: { } },
} as ActivatedRoute;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [UiTestModule],
declarations: [AppComponent],
providers: [
AppService,
JhiParseLinks,
Principal,
{
provide: ActivatedRoute,
useValue: {
data: {
// subscribe: (fn: (value: Data) => void) => fn({
subscribe: (fn: () => void) => fn({
// company: COMPANY,
pagingParams: {
page: 1
}
}),
},
params: {
// subscribe: (fn: (value: Params) => void) => fn({
subscribe: (fn: () => void) => fn({
tab: 0,
}),
},
snapshot: {
url: [
{
path: 'foo',
},
{
path: 'bar',
},
{
path: 'baz',
},
],
},
},
},
{ provide: Router, useValue: null },
JhiEventManager,
DomSanitizer,
ToasterAlertService,
AccountService,
ToastsManager,
ToastOptions
]
}).overrideTemplate(AppComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
// service = fixture.debugElement.injector.get(JhiHealthService);
});
describe('TODO3', () => {
it('TODO4', () => {
expect(comp.foo()).toEqual('bar');
});
});
});