Angular 角度8测试时无法获取喷油器
我在这里创建了一个示例项目。示例项目有两个组件(TestComponent和Test1Component)、一个服务(TestService)和一个类(Base),TestComponent将对其进行扩展 有一个用例,我需要在不使用构造函数的情况下获取服务实例,我正在使用下面的代码,它可以正常工作 应用模块:Angular 角度8测试时无法获取喷油器,angular,angular8,angular-test,Angular,Angular8,Angular Test,我在这里创建了一个示例项目。示例项目有两个组件(TestComponent和Test1Component)、一个服务(TestService)和一个类(Base),TestComponent将对其进行扩展 有一个用例,我需要在不使用构造函数的情况下获取服务实例,我正在使用下面的代码,它可以正常工作 应用模块: @NgModule({ imports: [ BrowserModule, FormsModule,], declarations: [ AppComponent, T
@NgModule({
imports: [ BrowserModule, FormsModule,],
declarations: [ AppComponent, TestComponent, Test1Component ],
bootstrap: [ AppComponent ],
exports: [TestComponent, Test1Component]
})
export class AppModule {
static injector: Injector;
constructor(injector: Injector) {
AppModule.injector = injector;
}
}
然后是Base.ts
export class Base {
constructor() {
console.log("i am base");
let service = AppModule.injector.get(TestService); // with this i can get test service succesfully
}
}
当我尝试为TestComponent编写测试用例时,会抛出错误,请参阅下面的代码,我不知道为什么会发生这种情况,请帮助。。。谢谢
describe("TestComponent", () => {
// throws error, Error during loading: Uncaught ReferenceError: Cannot access 'TestComponent' before initialization
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [AppModule]
}).compileComponents();
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it("should create", () => {
expect(component).toBeTruthy();
});
});
- 更新
以将karma.config.js
用作Angular cli
})); };module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false
服务器运行程序将在端口上侦听9876
- 然后使用
tsconfig.json
中的types选项自动导入类型:
“类型”:[“茉莉花”]
- 在
test.service.ts
中,它必须包含规范导入
因此,要使示例正常工作,只需更新test.service.ts
,并使其包含以下行:
import './test/test.component.spec';
对于运行测试,您应该使用测试运行程序作为Karma
而不是Node
,因为它不知道您的测试框架嗨,谢谢您的评论,实际上我不知道如何在stackblitz中运行ng测试,这只是为了代码演示。我正在使用ng cli以相同的代码在my local中创建项目,但即使我添加了您建议的行,它仍会在my local中引发相同的错误。请尝试此操作,并通过插入错误消息的快照来更新帖子,好吗
import './test/test.component.spec';