繁体   English   中英

当我的服务的构造函数中有可注入对象时,如何将服务注入我的测试中?

[英]How can I Inject a Service into my test when my service has an injectable in its constructor?

我想为我的DataService类创建一个测试脚本。 我知道我需要将服务注入到类中,但是DataService构造函数采用Apollo可注入对象。 我发现了一些过时的解决方案不起作用。 任何帮助将不胜感激!

@Injectable()
export class DataService {

    constructor(private apollo: Apollo) {}

    ...

}

这是我需要DataService的测试:

const chai = require('chai');
const should = chai.should();
const req = require("request-promise");
import {inject} from  "@angular/core/testing";
import { DataService } from '../data.service'

describe('User', () => {


    beforeEach(() => {

    })

    it('Can be created.', (done) => {

    });
})

您将要创建一个具有提供程序列表的TestModule,从本质上讲,这是Angular2遵循的规则,用于在请求某些内容时注入内容。

beforeEach(() => {

  TestBed.configureTestingModule({
    providers: [Apollo] // This will return an instance of the actual Apollo class (you will need to import Apollo in your spec file)
  }).compileComponents();

});

这将允许您将Apollo服务注入正在测试的代码中。 但是,您可能不希望注入实际的Apollo服务,在这种情况下,您可以创建一个模拟的Apollo类,并告诉测试组件注入该伪造的类来代替Apollo

class MyMockApollo {...} // should mock up any methods that your tests will rely on

beforeEach(() => {

  TestBed.configureTestingModule({
    providers: [
      {provide: Apollo, useClass: MyMockApollo} // This will return an instance of MyMockApollo
    ]
  }).compileComponents();

});

第三种选择是提供一个而不是一个

 providers: [
      {provide: Apollo, useValue: mockApolloInstance} // This will return the exact thing you give it
    ]

暂无
暂无

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

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