Pre*_*lan 6 javascript unit-testing jasmine angular
我有一个可注入服务(EntityApi),它扩展了一个类(BaseApi)。在我的规范中,我喜欢用 BaseApiStub 模拟 BaseApi。但这是徒劳的。总是调用 EntityApi。
// class
export class BaseApi { // want to mock BaseApi
constructor(injector: Injector) {
console.log("Should not be here...");
}
}
// service
@Injectable()
export class EntityApi extends BaseApi {
constructor(injector: Injector) {
super(injector, "entity");
}
}
// component
@Component({
selector: 'rt-entity-list',
templateUrl: './entity-list.component.html',
})
export class EntityListComponent {
api: any;
constructor(public entityApi: EntityApi) {
this.api = entityApi;
}
}
// mock api
export class BaseApiStub { //mocked api
constructor() {
console.log("You are on track!!")
}
get() { }
}
// spec
describe('EntityListComponent', () => {
let component: EntityListComponent;
let fixture: ComponentFixture<EntityListComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [EntityListComponent],
providers: [ { provide: BaseApi, useClass: BaseApiStub }, // mocked class.
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
beforeEach(() => {
fixture = TestBed.createComponent(EntityListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});Run Code Online (Sandbox Code Playgroud)
预期行为是,而在规范中编译组件。它应该调用 BaseApiStub,而不是调用 BaseApi。我已经看到了如下解决方案。但没有运气。
export class BaseApiStub extends BaseApi { }
Run Code Online (Sandbox Code Playgroud)
测试代码:stackblitz检查控制台。我希望你走上正轨!!登录但收到为不应该在这里...
无法进一步发展。有人可以纠正我的错误吗?
你想做的事是行不通的。依赖注入和类继承没有直接关系。这意味着您不能像这样切换服务的基类。
据我所知,您有两种方法可以做到这一点。
选项1:
您需要模拟 EntityApi 并在测试中提供此模拟,而不是模拟您的 BaseApi 并在测试中提供模拟。
选项2:
您可以将 BaseApi 保留为一个简单的服务并将其作为依赖项提供,而不是让 EntityApi 从 BaseApi 扩展。
代替
class EntityApi extends BaseApi {
constructor(private injector: Injector) {
Run Code Online (Sandbox Code Playgroud)
你做
class EntityApi {
constructor(private api: BaseApi) {
Run Code Online (Sandbox Code Playgroud)
如果您像这样设置 EntityApi,它不会从 BaseApi 扩展,而是将其作为依赖项。然后,您可以创建 BaseApi 的模拟并像在测试中那样提供它。
编辑
关于您的评论:
由于我应该使用 BaseApi 中的方法,所以我不能没有扩展。
这不是真的。假设 BaseApi 有一个您想要使用的方法 foo()。当您扩展基类时,用法可能如下所示:
class EntityApi extends BaseApi {
constructor(private injector: Injector) {}
exampleMethod() {
this.foo();
}
}
Run Code Online (Sandbox Code Playgroud)
如果您只有依赖项,您仍然可以像这样调用该方法:
class EntityApi {
constructor(private api: BaseApi) {}
exampleMethod() {
this.api.foo();
}
}
Run Code Online (Sandbox Code Playgroud)
您无需从 BaseApi 扩展即可调用其上的方法。
| 归档时间: |
|
| 查看次数: |
7656 次 |
| 最近记录: |