我正在做一个简单的小吃店,代码如下。
app.component.ts.cn
ngOnInit(){
this.dataService.valueChanges.pipe(
filter((data) =>data=== true),
switchMap(() => {
const snackBarRef = this.matSnackBar.open(
'A new value updated',
'OK',
{
duration: 3000
}
);
return snackBarRef.onAction();
})
)
.subscribe(() => {
this.window.location.reload();
});
}
app.component.spec.ts (包括服务的模拟数据)
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let matSnackBarSpy: jasmine.SpyObj<MatSnackBar>;
let a = "";
let b = "";
let c = "";
const mockDataService = {
valueChanges: of(true)
};
beforeEach(async(() => {
TestBed.configureTestingModule({
a = "Test";
b = "X";
c = "suc";
matSnackBarSpy = TestBed.get<MatSnackBar>(MatSnackBar);
})
}))
describe('#ngOnInit()', () => {
it('should call MatSnackBar.open()', async(done: DoneFn) => {
const error = new HttpErrorResponse({ error: 'Some error' });
component.ngOnInit();
expect(mockDataService.valueChanges).toBeTruthy();
expect(matSnackBarSpy.open(a,b,c)).toBeTruthy();
done();
});
});
})
data.service.ts
import { Observable } from 'rxjs';
export class DataService {
valueChanges: Observable<boolean>;
}
解释。
我有一个服务,它的属性是 valueChanges
类型为 Observable<boolean>
.
在 component.ts
我得到的值变化就像上面提到的那样,最终我收到的结果是布尔值 true
snackbar也被打开,一切正常。
现在,我进入了上述测试用例的实施阶段,如在 compoenent.spec.ts
,
expect(mockDataService.valueChanges).toBeTruthy();
expect(matSnackBarSpy.open(a,b,c)).toBeTruthy();
这样做的结果是成功的案例,但我在chrome中永远收到下面这个输出。
要求: 需要覆盖所有的测试,目前显示警告显示未覆盖在上图中。
以上测试用例正在运行,但测试覆盖率仍然显示为 功能不包括 并 声明不包括 开启时的警告 index.html
的组件。
所以,你基本上应该测试是否 matSnackBar
方法是否被正确调用。测试 matSnackBar
不是单元测试。
试试
class MatSnackBarStub{
open(){
return {
onAction: () => of({})
}
}
}
在 component.spec
档案
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers ; [ { provide: MatSnackBar , useClass: MatSnackBarStub }]
}).compileComponents();
}));
it('should create', () => {
spyOn(component.matSnackBar,"open").and.callThrough();
component.ngOnInit();
expect(component.matSnackBar.open).toHaveBeenCalled();
// you can also use ".toHaveBeenCalledWith" with necessary params
});
我建议你看看 本集 使用茉莉花和karma进行单元测试的相关内容。有一篇文章介绍了如何使用stubs和spies。我希望这能帮助到你