首页 > 解决方案 > 如何在 Angular 7 的 beforeEach Karma/Jasmine 测试中将服务注入自定义类?

问题描述

嗨我正在尝试测试自定义类实例化,我在同一个规范文件中有几个测试,这就是为什么使用该beforeEach方法,我也使用inject方法来获取我的类所需的服务,但是当我运行测试时,varappointmentCreationVehicle是未定义这是我的代码:

describe('AppointmentCreationVehicle', () => {
  let appointmentCreationVehicle: AppointmentCreationVehicle;

  beforeAll(() => {
    TestBed.configureTestingModule({
      imports: [AppModule]
    })
    .compileComponents();
  });

  beforeEach(
    inject([AppointmentCreationVehicle], (vehicleRestService: VehicleRestService) => {
      appointmentCreationVehicle = new AppointmentCreationVehicle(vehicleRestService);
    })
  );
  it('should create an instance',() => {
      expect(appointmentCreationVehicle).toBeTruthy();
  });

然后我的 karma.conf.js 看起来像这样:

module.exports = function (config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine', '@angular-devkit/build-angular'], 
        plugins: [
            require('karma-jasmine'),
            require('karma-firefox-launcher'),
            require('karma-mocha-reporter'),
            require('@angular-devkit/build-angular/plugins/karma')
        ],
        client: {
            clearContext: false, // leave Jasmine Spec Runner output visible in browser
            jasmine: {
                random: false
            },            
            captureConsole: true,
            mocha: {
                bail: true
            }        
        },
        reporters: ['mocha'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: ['HeadlessFirefox'],
        singleRun: true,
        customLaunchers: {
            HeadlessFirefox: {
                base: 'Firefox',
                flags: ['-headless']
            },
            ChromeDebugging: {
                base: 'Chrome',
                flags: ['--remote-debugging-port=9876']
            }
        }
    });
};

有可能在它执行之后服务的注入结束吗?如果我展示,我该如何避免这种行为。

标签: angularkarma-jasmine

解决方案


您没有将提供程序导入您的测试平台:

beforeAll(() => {
  TestBed.configureTestingModule({
    providers: [...] // <---------- HERE
  })
  .compileComponents();
});

之后,让它更简单:使用测试平台!它包含依赖项的 weekMap :

const myServiceInstance = TestBed.get(MyService);

推荐阅读