我正在制作一个简单的 snackbar ,其代码如下,
app.component.ts:
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
,我得到的值变化如上所述,我收到的最终结果是 bool 值true
并且 snackbar 也打开了,一切都工作正常。现在我正在实现上述测试用例,如
compoenent.spec.ts
,expect(mockDataService.valueChanges).toBeTruthy(); expect(matSnackBarSpy.open(a,b,c)).toBeTruthy();
这会导致成功,但我永远在 Chrome 中收到以下输出。
- 但我已经尝试过引用 Mocking MatSnackBar in Angular 8 & Jasmine但这没有帮助。
要求:需要涵盖当前显示上图中未涵盖的警告/指示的所有测试。
上述测试用例正在运行,但测试覆盖率在我们打开时仍显示函数未覆盖以及语句未覆盖警告 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
});
我建议你看看this collection of articles与使用 jasmine 和 karma 的单元测试相关。有一篇文章介绍如何使用 stub 和 spy 。我希望这会有所帮助
关于angular - 测试 Angular snackbar ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61929570/