繁体   English   中英

Angular 小吃店服务茉莉花测试

[英]Angular snackbar service jasmine testing

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

  1. 服务已创建
  2. 里面的方法被调用

小吃店服务

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

小吃店.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(Platform: core)[MatSnackBar]: NullInjectorError: No provider for MatSnackBar!
  2. SnackbarService > 应该被创建 NullInjectorError: StaticInjectorError(DynamicTestModule)[MatSnackBar]: StaticInjectorError(Platform: core)[MatSnackBar]: NullInjectorError: No provider for 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东西进行过单元测试,但是如果你遇到问题,请调查一下( 为具有 NgZone 依赖项的组件运行 jasmine 测试)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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