【发布时间】:2018-01-07 11:43:10
【问题描述】:
我正在尝试对我的组件进行单元测试,但基本测试失败。cannot resolve all parameters for MyComponent(?.)
我尝试在组件的构造函数中添加 forwardRef() ,但它可以工作。但我不想仅仅因为测试失败而使用它,不推荐使用它。
如有错别字请忽略。我已经添加了代码 sn-p。抱歉,我无法在此处添加实际代码。
源
./services
my-service-c.ts
import { MyServiceQ } from './my-service-q';
...
@Injectable()
export class MyServiceC {
constructor(private myServiceQ: MyServiceQ) { }
...
getMyServiceQ(){
return this.myServiceQ;
}
}
./components
my-component.ts
import { MyServiceC } from '../services/my-service-c';
@Component() {...}
export class MyComponent {
private myServiceQ;
constructor(private myServiceC: MyServiceC) {
this.myServiceQ = this.myServiceC.getMyServiceQ();
}
}
my-component.spec.ts
import { MyServiceC } from '../services/my-service-c';
import { MockMyServiceC } from '../fixtures/mock-my-service-c';
import { MyComponent } from './my-component';
..other imports...
beforeEach( () => {
TestBed.configureTestingModule({
providers: [
{ provide: MyServiceC, useClass: MockMyServiceC }
],
declarations: [ MyComponent ]
});
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be defined',
() => expect(component).toBeDefined();
);
如果您有任何建议,请告诉我。我一直在努力寻找解决方案。 提前谢谢..
【问题讨论】:
-
在我查看您的测试之前,请问您为什么要这样处理您的服务?为什么不直接在组件中注入
serviceQ? -
抱歉,这是要求。我不应该直接暴露 serviceQ。
-
好的,但它似乎是一个
Injectable(),所以你也必须提供它,或者它是如何注入到你的MockMyServiceC中的? -
@lexith 是的,抱歉,已删除;我误读了这个例子。 OP,请给一个连贯的minimal reproducible example,这里的省略号没有多大意义。
-
@jonrsharpe 没问题 :)
标签: angular unit-testing dependency-injection angular-components