角质小吃店茉莉花测试

问题描述 投票:0回答:1

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

  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没有提供程序!

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

谢谢!

angular unit-testing service jasmine snackbar
1个回答
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),请仔细研究。

© www.soinside.com 2019 - 2024. All rights reserved.