简体   繁体   中英

Angular Jest or Jasmine Testing: How to Properly Spy/Mock a Static Object Called From Within a Tested Class?

I have an AppConfigService that loads an object from a JSON file into a static settings variable that is part of the service. Various components and/or services throughout the application reference the object with AppConfigService.settings., with a simple reference (no injection). How can I test a service that is referencing this kind of construction?

For example

@Injectable()
export class SomeService {
someVariable;
  constructor() {
    // I can't get the test to not give me a TypeError: Cannot read property 'someSettingsVariable' of undefined on this line
    this.someVariable = AppConfigService.settings.someSettingsVariable;
  }
}

I have two projects, one using Jest and another Jasmine/Karma and I need to figure out the pattern of how to get the test to work in this construction.

I have tried things like:

const spy = spyOnProperty(SomeService, 'someVariable')
        .and.returnValue('someValue');

Example spec:

import { TestBed } from '@angular/core/testing';
import { NgRedux } from '@angular-redux/store';
import { Injectable } from '@angular/core';
import { DispatchHelper } from '../reducers/dispatch.helper';
import { ContributorActions } from '../actions/contributor.action';
import { MockDispatchHelper } from '../_mocks/DispatchHelperMock';
import { DiscrepancyService } from '../discrepancies/discrepancy.service';
import { DiscrepancyAPIService } from '../discrepancies/discrepancy-api.service';
import { DiscrepancyAPIServiceMock } from '../_mocks/DiscrepancyAPIServiceMock';
import { Observable } from 'rxjs';
import { Guid } from 'guid-typescript';
import { getInitialUserAccountState } from '../functions/initial-states/user-account-initial-state.function';
import { LoggingService } from '../security/logging/logging.service';
import { MockLoggingService } from '../_mocks/LoggingServiceMock';

describe('discrepancyService', () => {

    let discrepancyService: DiscrepancyService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                { provide: Injectable, useClass: Injectable },
                { provide: DispatchHelper, useClass: MockDispatchHelper },
                { provide: ContributorActions, useClass: ContributorActions },
                { provide: NgRedux, useClass: NgRedux },
                { provide: DiscrepancyService, useClass: DiscrepancyService },
                { provide: DiscrepancyAPIService, useClass: DiscrepancyAPIServiceMock },
                { provide: LoggingService, useClass: MockLoggingService },
            ]
        })
            .compileComponents();

        const userStateObservable = Observable.create(observer => {
            const userState = getInitialUserAccountState();
            userState.userId = Guid.parse('<guid>');
            userState.organization_id = Guid.parse('<guid>');
            observer.next(userState);
            console.log('built user state observable');
            observer.complete();
        });

        discrepancyService = TestBed.get(DiscrepancyService);
        const spy4 = spyOnProperty(discrepancyService, 'userState$', 'get').and.returnValue(userStateObservable);
    });


    // TODO: Fix this
    it('should create service and loadDiscrepancies', () => {
      // in this example, discrepancyService constructor sets the
      // value of a variable = ApiConfigService.settings.endPoint
      // ApiConfigService.settings is static; how do I "replace"
      // the value of endPoint in a call like this so I don't get
      // an error because ApiConfigService.settings is undefined
      // when called from a service in the test?
      const spy = spyOn(discrepancyService.dispatcher, 'dispatchPayload');
      discrepancyService.loadDiscrepancies();
      expect(spy.calls.count()).toEqual(1);
    });

});

karma.conf.js

// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma'),
      require('karma-spec-reporter')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    customLaunchers: {
      ChromeDebug: {
        base: 'Chrome',
        flags: [ '--remote-debugging-port=9333','--disable-web-security' ]
      },
      ChromeHeadlessCI: {
        base: 'Chrome',
        flags: ['--no-sandbox', '--headless', '--watch=false'],
        browserDisconnectTolerance: 10,
        browserNoActivityTimeout: 10000,
        browserDisconnectTimeout: 5000,
        singleRun: false
      }
    },
    reporters: ['progress', 'kjhtml', 'spec'],
    port: 9876,
    host: 'localhost',
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['ChromeDebug', 'ChromeHeadlessCI'],
    singleRun: false
  });
};

Any assistance from testing gurus would be appreciated.

Three ways I can see about it

Set the value directly

// TODO: Fix this
it('should create service and loadDiscrepancies', () => {
  // in this example, discrepancyService constructor sets the
  // value of a variable = ApiConfigService.settings.endPoint
  // ApiConfigService.settings is static; how do I "replace"
  // the value of endPoint in a call like this so I don't get
  // an error because ApiConfigService.settings is undefined
  // when called from a service in the test?
  AppConfigService.settings = { endpoint: 'http://endpoint' }
  const spy = spyOn(discrepancyService.dispatcher, 'dispatchPayload');
  discrepancyService.loadDiscrepancies();
  expect(spy.calls.count()).toEqual(1);
});

Add a null check and a setter

@Injectable()
export class SomeService {
someVariable;
  constructor() {
    // I can't get the test to not give me a TypeError: Cannot read property 'someSettingsVariable' of undefined on this line
    if (AppConfigService && AppConfigService.settings) {
        this.someVariable = AppConfigService.settings.someSettingsVariable;
    }
  }
}

set endPoint(value) {
    this.someVariable = value
}

Hide the static implementation behind a service

This for me is by far the best solution. Instead of going with a static implementation, create a single instance service that can be spied upon easily. This is not only a problem for you as you can imagine, but a problem for all OOP languages where the static implementations are avoid.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ConfigService {
  private endpoint: string;
  constructor() { }
  get endPoint(): string {
      return this.endPoint;
  }
}

Full example for runtime angular configuration here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM