[英]Angular2 test fail when mocking a service
Trying to test a component with a service dependency that call rest API, made a mocked version of the service, with a class that extends the real service. 尝试使用调用rest API的服务依赖项来测试组件,使用扩展实际服务的类来创建服务的模拟版本。
Now if I override the provider with the mocked one, weird error comes out of karma reporter, first 404 for 2 not existing files (that really should not exist) and then "{originalErr: {}}". 现在,如果我用模拟的覆盖提供者覆盖提供者,那么奇怪的错误来自业力记者,首先是404不存在的文件(真的不应该存在),然后是“{originalErr:{}}”。 I mean at least tell me what I've done wrong :) 我的意思是至少告诉我我做错了什么:)
describe('App: HeaderComponent', () => {
it('should get categories on initialization',
async(
inject([TestComponentBuilder], (builder: TestComponentBuilder) => {
let fixture: ComponentFixture<HeaderComponent>;
expect(builder).toBeDefined();
return builder
.overrideProviders(HeaderComponent, [{provide: CategoryService, useClass: MockCategoryService}])
.createAsync(HeaderComponent).then((_fixture) => {
fixture = _fixture;
let $el = fixture.debugElement;
let el = $el.nativeElement;
let component = $el.componentInstance;
component.ngOnInit();
fixture.detectChanges();
expect(el.querySelector('a')).toHaveText('Electric');
});
})
)
);
});
01 08 2016 11:58:29.684:WARN [karma]: No captured browser, open http://localhost:9876/
01 08 2016 11:58:29.713:INFO [karma]: Karma v1.1.2 server started at http://localhost:9876/
01 08 2016 11:58:29.718:INFO [launcher]: Launching browser Chrome with unlimited concurrency
01 08 2016 11:58:29.729:INFO [launcher]: Starting browser Chrome
01 08 2016 11:58:32.277:INFO [Chrome 52.0.2743 (Windows 10 0.0.0)]: Connected on socket /#Semtu7s7yqM-TW0GAAAA with id 14496897
01 08 2016 11:58:35.315:WARN [web-server]: 404: /base/dist/app/shared/services.js
01 08 2016 11:58:35.318:WARN [web-server]: 404: /base/dist/app/shared/services/mocks.js
Chrome 52.0.2743 (Windows 10 0.0.0) ERROR
{
"originalErr": {}
}
If i remove the line the test pass (but doesn't execute the "then(...)" code block): 如果我删除测试通过的行(但不执行“then(...)”代码块):
overrideProviders(HeaderComponent, [{provide: CategoryService, useClass: MockCategoryService}])
Well, in case anybody encounter the same problem, it turned out one should import the "ts" file itself, not through a barrel. 好吧,如果有人遇到同样的问题,原来应该导入“ts”文件本身,而不是通过桶。 meaning you should write something like this: 意思是你应该写这样的东西:
import { CategoryService } from '../../shared/services/category/category.service';
import { MockCategoryService } from '../../shared/services/category/category.service.mock';
instead of 代替
import { CategoryService, MockCategoryService } from '../../shared/services/category';
even though you have index.ts in the directory that export the files. 即使您在导出文件的目录中有index.ts。
Wierd, Huh? 哇,嗯?
Still the problem of not executing the async operation exist, I don't know why 仍然存在不执行异步操作的问题,我不知道为什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.