Angular 小吃店服务茉莉花测试

Angular snackbar service jasmine testing

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

  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();
  })
});

在 运行 测试之后,Karma 给我以下错误:

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

关于如何解决这个问题有什么想法吗?

谢谢!

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

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)。