简体   繁体   English

Angular-Cli-测试服务

[英]Angular-cli - Test Service

I'm using the angular-cli and have tried to get into the habbit of testing my services, but I can't seem to inject the service into the test here's my situation: 我正在使用angular-cli并试图进入测试我的服务的习惯,但是我似乎无法将服务注入测试中,这是我的情况:

Angular2 Service Angular2服务

@Injectable()
export class AppService{
}

Karma Test - V1.3.0 业力测试-V1.3.0

Is this the correct syntax? 这是正确的语法吗? It seems it's changed throughout the initial release of angular2. 似乎在整个angular2的初始发行版中它都发生了变化。

describe('Tests', () => {
  beforeEach(() => [
    {provide: AppService, useClass: AppService}
  ]);

  it('should create an instance', inject([AppService], (service: AppService) => {
    expect(service).toBeTruthy();
  }));
});

Is this the correct syntax? 这是正确的语法吗? It seems it's changed throughout the initial release of angular2. 似乎在整个angular2的初始发行版中它都发生了变化。

Test Error 测试错误

Tests should create an instance FAILED
    Error: No provider for AppService!

My Configuration 我的配置

angular-cli: 1.0.0-beta.21
node: 6.5.0
os: win32 x64

If you want to inject it, you still need to use the TestBed to configure the Angular test environment 如果要注入它,仍然需要使用TestBed来配置Angular测试环境

import { TestBed } from '@angular/core/testing';

beforeEach(() => TestBed.configureTestingModule({
  providers: [ {provide: AppService, useClass: AppService} ]
}));

*Note:** If the service doesn't have any other dependencies, you might just want to forget the Angular configuration, and just do an isolated test by instantiating the service yourself. *注意:**如果该服务没有任何其他依赖项,则您可能只想忘记Angular配置,而只是通过自己实例化该服务来进行隔离测试。

let service = new AppService();

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM