angular - 测试角小吃吧
问题描述
我正在制作一个简单的小吃店,其代码如下,
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();
});
});
})
数据服务.ts
import { Observable } from 'rxjs';
export class DataService {
valueChanges: Observable<boolean>;
}
解释:
我有一项服务,其
valueChanges
类型为Observable<boolean>
.在
component.ts
中,我得到了如上所述的值变化,我收到的最终结果是布尔值true
,并且小吃店也被打开,一切正常。现在我正在执行上述测试用例,
compoenent.spec.ts
例如expect(mockDataService.valueChanges).toBeTruthy(); expect(matSnackBarSpy.open(a,b,c)).toBeTruthy();
这导致成功案例,但我永远在 chrome 中收到以下输出。
- 但是我已经在 Angular 8 和 Jasmine 中参考Mocking MatSnackBar 进行了尝试,但它没有帮助。
要求:需要涵盖当前显示警告/指示上图中未涵盖的所有测试。
上面的测试用例正在运行,但是当我们打开组件时,测试覆盖率仍然显示功能未覆盖,并且语句未覆盖警告。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
});
我建议你看看这个与使用 jasmine 和 karma 进行单元测试相关的文章集合。有一篇关于如何使用存根和间谍的文章。我希望这会有所帮助
推荐阅读
- function - 在 db2 的函数中返回游标
- python - 输出度量 TP、NP、TN、FN 值,用于留一出随机森林模型 python
- javascript - 如何以与调用函数的循环方式相同的顺序从 API 返回 res?
- mysql - MySQL 将字母转换为数字(例如,'A' 转换为 1,'B' 转换为 2...)
- wordpress - 使用 flamingo 和联系表 7 中存储的数据并将其显示在结帐页面字段中
- c# - 如何在堆积条形图上显示平均计数而不是总数?
- java - 多个相同长度的模型同时迭代
- android - 如何使用 Image.memory() 或 MemoryImage() 缓存内存图像?
- terraform - .terraform.lock.hcl 是否应该包含在 .gitignore 文件中?
- reactjs - 无法使用 cytoscape.js 制作非常基本的有向图并做出反应