【发布时间】:2020-06-30 15:29:33
【问题描述】:
我想用 jasmine 测试小吃店服务。更具体地说,我正在测试以下两种情况:
- 服务已创建
- 里面要调用的方法
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 给我以下错误:
- SnackbarService > 应该调用 open() NullInjectorError:StaticInjectorError(DynamicTestModule)[MatSnackBar]: StaticInjectorError(平台:核心)[MatSnackBar]: NullInjectorError:没有 MatSnackBar 的提供者!
- SnackbarService > 应该被创建 NullInjectorError:StaticInjectorError(DynamicTestModule)[MatSnackBar]: StaticInjectorError(平台:核心)[MatSnackBar]: NullInjectorError:没有 MatSnackBar 的提供者!
关于我应该如何解决这个问题的任何想法?
谢谢!
【问题讨论】:
标签: angular unit-testing service jasmine snackbar