我对 Angular Material 单元测试和服务单元测试都比较陌生。我为我的应用程序创建了一个服务,我可以使用它调用 Material SnackBar 打开函数并传递一个消息参数。它在需要时在每个组件中都可以正常工作,但是对它的单元测试对我来说很糟糕。
import { Injectable } from '@angular/core';
import { MatSnackBar, MatSnackBarRef, MatSnackBarConfig } from '@angular/material/snack-bar';
@Injectable({
providedIn: 'root',
})
export class NotificationService {
private snackBarConfig: MatSnackBarConfig;
private snackBarRef: MatSnackBarRef<any>;
private snackBarAutoHide = '5000';
constructor(private sb: MatSnackBar) {}
openSnackBar(message) {
this.snackBarConfig = new MatSnackBarConfig();
this.snackBarConfig.duration = parseInt(this.snackBarAutoHide, 0);
this.sb.open(message, 'Dismiss', this.snackBarConfig);
}
}
而所谓的测试规范文件是这样的:
import { Overlay } from '@angular/cdk/overlay';
import { TestBed } from '@angular/core/testing';
import { MatSnackBar } from '@angular/material/snack-bar';
import { createServiceFactory, SpectatorService } from '@ngneat/spectator';
import { NotificationService } from './notification-service';
describe('NotificationService testing:', () => {
let spectator: SpectatorService<NotificationService>;
const createService = createServiceFactory({
service: NotificationService,
providers: [MatSnackBar, Overlay],
entryComponents: [],
mocks: [NotificationService],
});
beforeEach(() => (spectator = createService()));
it('should openSnackBar() be known as function', () => {
expect(typeof spectator.service.openSnackBar).toEqual('function');
});
it('should be created', () => {
const dateService = spectator.inject(NotificationService);
spyOn(spectator.service, 'openSnackBar');
dateService.openSnackBar('Test');
expect(spectator.service.openSnackBar).toHaveBeenCalledWith('Test');
});
});
我的问题如下:
- 为什么我的业力报道说 openSnackBar(message) 方法没有经过测试?我的意思是至少我测试它是否是一个函数。
- 我如何才能真正独立地测试这样的服务?
先感谢您。