角小吃吧服务茉莉花测试

时间:2020-03-19 13:23:56

标签: angular unit-testing service jasmine snackbar

我想用茉莉花测试小吃店服务。更具体地说,我正在测试以下两种情况:

  1. 该服务已创建
  2. 其中要调用的方法

snackbar.service

import { Injectable, NgZone } from '@angular/core';
import { MatSnackBar } from '@angular/material';

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

  constructor(
    public snackBar: MatSnackBar,
    private zone: NgZone
  ) { }

  public open(message, action, duration = 1000) {
    this.zone.run(() => {
      this.snackBar.open(message, action, { duration });
    })
  }
}

snackbar.service.spec

import { TestBed } from '@angular/core/testing';
import { SnackbarService } from './snackbar.service';

describe('SnackbarService', () => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
    const service: SnackbarService = TestBed.get(SnackbarService);
    expect(service).toBeTruthy();
  });

  it('should call open()', () => {
    const service: SnackbarService = TestBed.get(SnackbarService);
    const spy = spyOn(service, 'open');
    service.open('Hello', 'X', 1000);
    expect(spy).toHaveBeenCalled();
  })
});

运行测试后,业力给我以下错误:

  1. SnackbarService>应该调用open() NullInjectorError:StaticInjectorError(DynamicTestModule)[MatSnackBar]: StaticInjectorError(平台:核心)[MatSnackBar]: NullInjectorError:MatSnackBar没有提供程序!
  2. SnackbarService>应该被创建 NullInjectorError:StaticInjectorError(DynamicTestModule)[MatSnackBar]: StaticInjectorError(平台:核心)[MatSnackBar]: NullInjectorError:MatSnackBar没有提供程序!

关于如何解决此问题的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:1)

是的,您必须导入并提供所需的内容。

import { TestBed } from '@angular/core/testing';
import { SnackbarService } from './snackbar.service';
import { MatSnackBarModule } from '@angular/material/snack-bar';

describe('SnackbarService', () => {
  let zone: NgZone;
  let snackBar: MatSnackBar;
  beforeEach(() => TestBed.configureTestingModule({
     imports: [MatSnackBarModule],
     providers: [
       SnackbarService,
       NgZone,
     ],
  }));

  beforeEach(() => {
    // if you're on Angular 9, .get should be .inject
    zone = TestBed.get(NgZone);
    spyOn(zone, 'run').and.callFake((fn: Function) => fn());
    snackBar = TestBed.get(MatSnackBar);
  });

  it('should be created', () => {
    const service: SnackbarService = TestBed.get(SnackbarService);
    expect(service).toBeTruthy();
  });

  // the way you have written this test, it asserts nothing
  it('should call open()', () => {
    const service: SnackbarService = TestBed.get(SnackbarService);
    // const spy = spyOn(service, 'open');
    const spy = spyOn(snackBar, 'open');
    service.open('Hello', 'X', 1000);
    expect(spy).toHaveBeenCalled();
  })
});

我从未对需要NgZone的东西进行单元测试,但是如果遇到问题(Running jasmine tests for a component with NgZone dependency),请仔细研究。