[英]How to unit test @hostlistener paste event using angular 7 karma/jasmine
[英]How to unit test MatSnackbar using Jasmine Karma in Angular
我想對這個 onSubmit 函數執行單元測試,其中肯定提交導致 MatSnackbar 消息“提交成功”。 我是 Jasmine Karma 的新手,請指導我在這種情況下測試 MatSnackbar。
組件.ts
import { MatSnackBar } from "@angular/material/snack-bar";
constructor(
private snackBar: MatSnackBar,
private auth: AuthenticateService,
) {}
...
...
onSubmit(e) {
const newYellow = {
G1: e.value.Yellow_G1,
G2: e.value.Yellow_G2,
G3: e.value.Yellow_G3,
G4: e.value.Yellow_G4,
B1: e.value.Yellow_B1,
B2: e.value.Yellow_B2,
B3: e.value.Yellow_B3,
B4: e.value.Yellow_B4,
};
console.log(newYellow);
this.auth.submitnominYellow(newYellow).subscribe(
(res) => {
console.log(res);
this.snackBar.open("Submitted Successfully", "", {
duration: 2000,
});
},
(error) => {
console.log(error);
}
);
}
這是submitnomin
函數的代碼。 auth.service.ts
submitnominYellow(inpobj) {
console.log(inpobj);
return this.http.post(environment.apiUrl + '/api/customize/yellow', inpobj);
}
我的單元測試用例有點像這樣。
組件.spec.ts
const mockSnackbarMock = jasmine.createSpyObj(['open']);
mockSnackbarMock.open
const mockopblue =
{
success: true
}
const MockAuthService = {
submitnominYellow:(id) => (mockopblue),
getuser:() => (undefined)
};
...
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ YellowCustomizeComponent ],
imports: [HttpClientTestingModule, MatSnackBarModule, FormsModule, RouterTestingModule],
providers:[{provide: MatSnackBar, useValue: mockSnackbarMock},
{provide: AuthenticateService, useValue: MockAuthService}
]
})
.compileComponents();
}));
...
fit('should open the snack bar with correct arguments when form submitted', () => {
const e = {
value:{
Yellow_G1: "YGirlName1",
Yellow_G2: "GirlName2",
Yellow_G3: "GirlName3",
Yellow_G4: "GirlName4",
Yellow_B1: "BoyName1",
Yellow_B2: "BoyName2",
Yellow_B3: "BoyName3",
Yellow_B4: "BoyName4",
}
};
component.onSubmit(e)
console.log('mockSnackbarMock',mockSnackbarMock)
// console.log('yellow onsubmit',component.onSubmit(e));
expect(mockSnackbarMock.open).toHaveBeenCalledWith("Submitted Successfully", "", );
})
在測試中,可以更改依賴項注入配置,以便提供模擬而不是SnackBar
實例。 那是如何做到的:
const mockSnackbarMock = jasmine.createSpyObj(['open']);
mockSnackbarMock.open
await TestBed.configureTestingModule({
declarations: [
...
],
providers: [
{provide: MatSnackBar, useValue: mockSnackbarMock},
],
imports: [
...
],
}).compileComponents();
稍后在所有觸發小吃店的操作之后的測試中,您可以檢查 open 方法是否被正確調用:
it('should open the snack bar with correct arguments when form submitted', () => {
//emulate submission
expect(mockSnackbarMock.open).toHaveBeenCalledWith("Submitted Successfully", "", {duration: 2000});
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.