我是新手,尤其是在单元测试方面。
最近,我一直在做一个组件,以使用来自角形材料(https://material.angular.io/components/snack-bar/overview)的Mat-Snack-Bar材料。
创建组件之后,我正在对该组件进行单元测试,以检查是否打开了小吃店的类。
我已经尝试应用一些我在堆栈溢出时发现的答案,但是我无法进行单元测试,因此我在Karma应用程序中始终出现此错误消息:
'TypeError:无法读取未定义的属性'openSnackBar'
我无法理解我的组件规格中发生了什么问题以及如何解决此错误。
我的component.ts:
import { Component, OnInit } from '@angular/core';
import { MatSnackBar ,MatSnackBarHorizontalPosition, MatSnackBarVerticalPosition, } from "@angular/material";
@Component({
selector: 'app-snack-bar',
templateUrl: './snack-bar.component.html',
styleUrls: ['./snack-bar.component.scss']
})
export class SnackBarComponent implements OnInit {
ngOnInit() {
}
constructor(public snackBar: MatSnackBar) {}
// Position of the snackbar
horizontalPosition: MatSnackBarHorizontalPosition = 'right';
verticalPosition: MatSnackBarVerticalPosition = 'top';
/**
* To use a snackbar add the function openSnackBar('','','')
* @param message Message that will be shown when the SnackBar is called
* @param action The message that will be shown on the action button
* @param state Permit to change the style of the SnackBar depending on the state
*/
openSnackBar(message: string, action: string, state: string) {
if ( state == 'suc') {
var styleOfSnack = 'sucessSnackbar';
} else if ( state == 'err') {
var styleOfSnack = 'errorSnackbar';
} else if ( state == 'inf') {
var styleOfSnack = 'infoSnackbar';
} else if ( state == 'war') {
var styleOfSnack = 'warningSnackbar';
}
// code linked to the snackbar
this.snackBar.open(message, action, {
duration: 8000,
panelClass: [styleOfSnack],
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
}
'''
这是我的component.spec.ts,用于验证代码:
describe('SnackBar should be open', () => {
let component: SnackBarComponent;
let a = "";
let b = "";
let c = "";
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ SnackBarComponent],
providers: [ MatSnackBar, Overlay ]
})
.compileComponents();
a = "Test";
b = "X";
c = "suc";
});
afterEach(() => {
a = "";
b = "";
c = "";
});
it('opens', () => {
expect(component.openSnackBar(a,b,c)).toHaveBeenCalled;
});
})
我希望单元测试检查是否调用了函数openSnackBar!
感谢您抽出宝贵的时间阅读我的问题,如果您有任何技巧或教程可以帮助初学者了解有关angular的单元测试,我将为您提供帮助!
答案 0 :(得分:0)
您没有初始化组件。
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ SnackBarComponent],
providers: [ MatSnackBar, Overlay ]
})
.compileComponents();
a = "Test";
b = "X";
c = "suc";
component = TestBed.get(SnackBarComponent);
});
您没有调用toHaveBeenCalled
函数。
it('opens', () => {
expect(component.openSnackBar(a,b,c)).toHaveBeenCalled();
});