设置角度“提供者”的基本单元测试

时间:2020-03-17 14:35:01

标签: angular typescript unit-testing ionic-framework karma-runner

我正在为我的角度应用程序(特别是离子应用程序)设置基本的单元测试。我正在使用离子团队预先配置的解决方案来使用业力/茉莉花。通过了包含的示例单元测试,因此我继续为自己的提供者编写了一个新的单元测试。

这是我遇到麻烦的地方,因为没有可供参考的真实示例。因此,我创建了一个TestBed,并按照您对应用程序的要求放置了最少的必需组件。但是,每次我运行单元测试时,都会出现一个模糊且无法描述的错误:Error: Illegal state: Could not load the summary for directive TestServiceProvider.

Error: Illegal state: Could not load the summary for directive TestServiceProvider.
            at syntaxError (webpack:///node_modules/@angular/compiler/esm5/compiler.js:486:21 <- karma-test-shim.js:66892:34)
            at CompileMetadataResolver.getDirectiveSummary (webpack:///node_modules/@angular/compiler/esm5/compiler.js:15085:0 <- karma-test-shim.js:81491:31)
            at JitCompiler.getComponentFactory (webpack:///node_modules/@angular/compiler/esm5/compiler.js:34301:25 <- karma-test-shim.js:100707:63)

查看堆栈跟踪,它看起来像是由SyntaxError引起的。尽管我不确定发生的原因和原因。知道这个示例做错了什么吗?

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

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

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

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

  it('should add numbers', () => {
    expect(1+1).toBe(2);
  });
});
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() {
    console.log('Hello TestServiceProvider Provider');
  }

}

1 个答案:

答案 0 :(得分:0)

您不需要创建组件实例,因为我们只是在测试服务。只需注入它并在测试规格中对其进行测试。以下是开始测试所需的最低代码。

from multiprocessing import Queue