【问题标题】:How to inject services in to a custom class in beforeEach Karma/Jasmine test in Angular 7?如何在 Angular 7 的 beforeEach Karma/Jasmine 测试中将服务注入自定义类?
【发布时间】:2019-05-29 11:21:37
【问题描述】:

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

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']
            }
        }
    });
};

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

【问题讨论】:

    标签: angular karma-jasmine


    【解决方案1】:

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

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

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

    const myServiceInstance = TestBed.get(MyService);
    

    【讨论】:

    • 我的 AppModule 中有提供程序。需要用 TestBed 导入吗?
    • @ErnestoAlfonso 也许你应该在测试之前阅读the documentation ...
    • 我的意思是,如果你连概念都不懂,为了测试而测试是没有意义的。
    • TestBed.configureTestingModule 生成一个用于测试的模块,它的工作方式与其他具有导入、提供程序等的模块一样,如果我将一个模块导入到 TestingModule 中,它将像我在我的一个应用程序中执行相同操作一样工作模块。
    • 这就是我的意思,你根本不熟悉单元测试的概念。花点时间,阅读文档,你就会明白你的错误。
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    相关资源
    最近更新 更多