gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:34:59 26 4
gpt4 key购买 nike

@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 is not an object (evaluating 's2.name')

因为 Service2 未定义。

相同的代码早先使用了 addProviders 和 provide

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

删除 console.log( s2.name ) 后,这 2 个测试通过了

有什么想法吗?

最佳答案

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

示例:

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

关于Angular 2 rc5,服务单元测试问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41484380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com