在离子提供者中设置试验台

时间:2017-10-22 17:02:58

标签: unit-testing ionic-framework karma-jasmine

我是Ionic和单元测试的新手。当前版本是3.12.0。我正在使用Karma和Jasmine进行单元测试。

我有一个名为 test-service.ts

的提供商
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the TestServiceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class TestServiceProvider {

  constructor(public http: Http) {
    console.log('Hello TestServiceProvider Provider');
  }

}

然后我在同一个文件夹中有一个测试规范,包含一个带测试台的简单测试。

import { TestServiceProvider } from './test-service';
import { TestBed, TestModuleMetadata, async, ComponentFixture } from '@angular/core/testing';

describe('Test Service', () => {
  let component: TestServiceProvider;
  let fixture: ComponentFixture<TestServiceProvider>;

  beforeEach(async( () => {
    TestBed.configureTestingModule({
      imports: [TestServiceProvider]
    }).compileComponents;
  }));

  beforeEach( () => {
    fixture = TestBed.createComponent(TestServiceProvider);
    component = fixture.componentInstance;
  });

  it('should add numbers', () => {
    expect(1+1).toBe(2);
  });
});

但是当我运行npm test时,它会给我一个错误

Unexpected value 'TestServiceProvider' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.

我在这里做错了什么,如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

TestServiceProvider必须在声明中,而不是在Imports

更改您的代码如下:

beforeEach(async( () => {
    TestBed.configureTestingModule({
      declarations: [TestServiceProvider]
    }).compileComponents;
  }));