我想用茉莉花测试小吃店服务。更具体地说,我正在测试以下两种情况:
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();
})
});
运行测试后,业力给我以下错误:
关于如何解决此问题的任何想法?
谢谢!
是,您必须导入并提供所需的内容。
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),请仔细研究。