我的问题类似于here找到的问题,但修复程序无法解决我的问题。我的项目使用Angular 4 v4.2.3,Karma v1.7.0,Jasmine v2.6.0和karma-jasmine v1.1.0。
即使规范文件与服务位于同一文件夹中,我也会收到以下错误。如果我注释掉beforeEach块,则" true等于true"测试工作正常。
未捕捉错误:无法找到./process-message.service [C:/Projects/myproject/Resources/app/services/process-message.service.ts] (要求 C:/Projects/myproject/Resources/app/services/process-message.service.spec.ts) at require(commonjs.js:13) at commonjs.js:18 at Object.global.wrappers.C:/Projects/myproject/Resources/app/services/process-message.service.spec.ts.@angular/core/testing (处理message.service.spec.ts:16) at require(commonjs.js:17) at commonjs.js:32 在Array.forEach() at commonjs.js:31 at commonjs.js:34
过程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);
}
}
这是我的规范文件
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
});
}