Angular 6+单元测试中的spyOn isDevMode()?

时间:2018-07-17 21:37:23

标签: angular unit-testing jasmine karma-jasmine

我的代码包括一个if

服务:

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

export class MyService {
  constructor() {}

  methodToTest(): {
    if (!isDevMode()) {
      doSomething();
    } else {
      doSomethingDifferentInDevMode();
    }
  }
}

my-service.spec.ts(仅相关行):

it('should run doSomething() when isDevMode() returns false', () => {
  // what should i do here to mock a false value return for isDevMode() ?
  expect(doSomething).toHaveBeenCalled();
});

对于该单个Angular单元测试,我如何监视isDevMode()使其返回false,以便我可以测试调用doSomething()的情况?

2 个答案:

答案 0 :(得分:3)

首先将此函数包装到服务中:

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

@Injectable({ providedIn: 'root' })
export class DevModeService {
  constructor() {}

  isDevMode() {
    return isDevMode();
  }
}

然后,您可以像使用任何其他服务一样在任意位置注入此服务:

import { DevModeService } from 'dev-mode.service';

export class MyService {
  constructor(private devModeService: DevModeService) {}

  methodToTest(): {
    if (!this.devModeService.isDevMode()) {
      doSomething();
    } else {
      doSomethingElse();
    }
  }
}

然后您可以在测试MyService时监视DevModeService,就像对其他依赖项所做的那样:

it('should do something when in dev mode') {
  const devModeService: DevModeService = TestBed.get(DevModeService);
  spyOn(devModeService, 'isDevMode').and.returnValue(true);

  const myService: MyService = TestBed.get(MyService);
  myService.methodToTest();
  // ...
}

it('should do something else when in prod mode') {
  const devModeService: DevModeService = TestBed.get(DevModeService);
  spyOn(devModeService, 'isDevMode').and.returnValue(false);

  const myService: MyService = TestBed.get(MyService);
  myService.methodToTest();
  // ...
}

答案 1 :(得分:0)

答案似乎在评论中。谢谢@JBNizet。

// dev-mode-service.ts

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

export class DevModeService {
  constructor() {}

  isDevMode(): {
    return isDevMode();
  }
}


// MyService.ts

import { isDevMode } from 'dev-mode-service';

export class MyService {
  constructor() {}

  methodToTest(): {
    if (!isDevMode()) {
      doSomething();
    } else {
      doSomethingDifferentInDevMode();
    }
  }
}