Angular4 Karma Jasmine Can't find the module under test

My problem is similar to the one found here , but the fix didn't resolve my problem. My project is using Angular 4 v4.2.3, Karma v1.7.0, Jasmine v2.6.0 and karma-jasmine v1.1.0.

I am getting below error even though the spec file is in the same folder as the service. If I comment out the beforeEach block, then the "true equals true" test works fine.

Problem: Unable to find. / process -message.service [C: /Projects/myproject/Resources/app/services/process-message.service.ts] (requires C: /Projects/myproject/Resources/app/services/process-message.service.spec .ts) when required (commonjs.js: 13) at commonjs.js: 18 in Object.global.wrappers.C: /Projects/myproject/Resources/app/services/process-message.service.spec.ts. @ angular / core / testing (process-message.service.spec.ts: 16) on demand (commonjs.js: 17) at commonjs.js: 32 in Array.forEach () at commonjs.js: 31 at commonjs.js : 34

Process-message.service

import { Injectable, Inject } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Subscriber } from 'rxjs/Subscriber';
import { APP_CONFIG, AppConfig } from '../app-config.module';
import { SensorMessage } from '../models/sensor-message';

// TODO: Remove mock data once application service layer is ready
import { MockSensorMessageData } from '../mock-data/mock.sensormessage.data'

@Injectable()
export class ProcessMessageService {
    private useMocks: boolean = true;

    constructor(
        @Inject(APP_CONFIG) private config: AppConfig,
        private http: Http
    ) { }

    getSensorMessages(): Observable<Array<SensorMessage>> {
        if (this.useMocks) {
            return new Observable<Array<SensorMessage>>(
                (subscriber: Subscriber<SensorMessage[]>) =>
                     subscriber.next(MockSensorMessageData)
            );
        } else {
        return Observable
            .interval(this.config.pollInterval)
            .flatMap(() => {
                return this.http
                    .get(`${this.config.apiEndpoint}/GetSensorMessages`, { headers: this.getHeaders() })
                    .map(this.mapSensorMessages)
                    .catch(this.handleError);
            });

        }
    }      

    private getHeaders(): Headers {
        const headers = new Headers();
        headers.append('Accept', 'application/json');
        return headers;
    }

    private handleError(error: any): Observable<any> {
        // TODO: Add global error handling
        const errorMsg = error.message || ' There was a problem retrieving data from the server';

        // throw an application level error
        return Observable.throw(errorMsg);
    }

}

      

Here's my spec file

import {
TestBed,
getTestBed,
async,
inject
} from '@angular/core/testing';
import {
Headers, BaseRequestOptions,
Response, HttpModule, Http, XHRBackend, RequestMethod
} from '@angular/http';

import { ResponseOptions } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

import { ProcessMessageService } from './process-message.service';
import { APP_CONFIG, AppConfig } from '../app-config.module';

describe('ProcessMessageService', () => {
    let mockBackend: MockBackend;

const APP_TEST_CONFIG = {
    apiEndpoint: 'http://127.0.0.1/test',
    pollInterval: 1000
};

beforeEach(async(() => {
    TestBed.configureTestingModule({
        providers: [
            ProcessMessageService,
            MockBackend,
            BaseRequestOptions,
            {
                provide: Http,
                deps: [MockBackend, BaseRequestOptions],
                useFactory:
                (backend: XHRBackend, defaultOptions: BaseRequestOptions) => 
                {
                    return new Http(backend, defaultOptions);
                }
            }
        ],
        imports: [
            HttpModule
        ]
        }).compileComponents();

        mockBackend = getTestBed().get(MockBackend);

    }));

    // just trying to get the tests to work
    describe('svc tests', () => {
        it('true is true', () => expect(true).toBe(true));
    });

    it('service should exist',
        inject([ProcessMessageService], (messageService: ProcessMessageService) => {
            expect(messageService).toBeDefined();
    }));
});

      

karma.conf.js

// Karma configuration
// Generated on Thu Jul 06 2017 07:44:59 GMT-0400 (Eastern Daylight Time)

module.exports = function (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', 'karma-typescript'],


        // list of files / patterns to load in the browser
        files: [
            { pattern: 'node_modules/zone.js/dist/zone.js', included: true, watched: true },
            'app/**/*.spec.ts'
        ],


        // list of files to exclude
        exclude: [
            // 'node_modules/**/*.ts'
        ],


        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            '**/*.ts': ['karma-typescript']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'kjhtml', 'karma-typescript'],


        // 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: true,


        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],


        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity
    });
}

      

+3


source to share





All Articles