Angular 2 rc5,与服务的单元测试问题

时间:2017-01-05 11:50:41

标签: angular jasmine

@Injectable()
export class Service1 {
    constructor( private s2 : Service2 ) { 
        console.log( s2.name );
     }
}

@Injectable()
export class Service2 {
    public name: string = 'Hi';
}


//------------Test-------------

let service1: MockService1;  // MockService1 extends Service1
let service2: MockService2;  // MockService2 extends Service2

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [
            { provide: Service1, useClass: MockService1 },
            { provide: Service2, useClass: MockService2 }
        ]
    })
});  

beforeEach(inject( [ Service1 , Service2 ], ( s1: MokcService1 , s2: MockService2  ) => { 
    service1 = s1;
    service2 = s2; 
}));

it('should be defined ', () => {
    expect( service1 ).toBeDefined(); 
    expect( service2 ).toBeDefined();
});

我正在

TypeError:undefined不是对象(评估' s2.name')

因为Service2未定义。

相同的代码早先使用addProviders并提供

beforeEach(() => {
    addProviders([
        provide(Service1, {useClass: MockService1 } ),
        provide(Service2, {useClass: MockService2 } ),
    ]);
});         

当删除console.log(s2.name)时,这两个测试正在通过

任何想法?

1 个答案:

答案 0 :(得分:0)

在构造函数中注入服务时使用@Inject,

示例:

constructor( @Inject(Service2) private s2 : Service2 ) { 
    console.log( s2.name );
}