我正在尝试为testComponent以下的内容编写茉莉花单元。这是我第一次编写单元测试用例。
这里我正试图通过click事件传递对象。但在spec.ts
文件中配置具有相同结构的测试数据时,会产生一点混乱。
进行测试时,我得到position
的undefined
到目前为止,我已经完成了下面的工作
<button (click)="clickToCheck();"> </button>
testComponent.ts
export class testComponent implements {
@Output() passVal = new EventEmitter();
@Input() checkEmployeePosition: any;
clickToCheck() {
const testData = {
position: this.checkEmployeePosition.level
};
this.passVal.emit(testData);
}
}
testComponent.spec.ts
import { DebugElement, ElementRef } from "@angular/core";
import {
TestBed,
ComponentFixture,
fakeAsync,
tick,
} from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { testComponent } from "./testComponent.component";
import { fileURLToPath } from "url"
fdescribe("testComponent", () => {
let fixture: ComponentFixture<testComponent>;
let component: testComponent;
let de: DebugElement;
let btn: ElementRef;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [testComponent],
});
});
beforeEach(() => {
fixture = TestBed.createComponent(testComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
btn = de.query(By.css("button"));
});
it("should create", () => {
expect(component).toBeTruthy();
});
describe("passVal", () => {
/*
let testData = {
name : 'hell0 world'
}
*/
it("should emit when the button is clicked", () => {
spyOn(component.passVal, "emit");
btn.nativeElement.click();
expect(component.passVal.emit).toHaveBeenCalledWith(1);
});
it("should emit when clickToCheck() is called", () => {
spyOn(component.passVal, "emit");
component.emitContinue();
expect(component.passVal.emit).toHaveBeenCalledWith(1);
});
it("should emit when the button is clicked", () => {
component.passVal.subscribe((next: any) => {
expect(next).toEqual(1);
});
btn.nativeElement.click();
});
});
});
请帮助我。
感谢所有人
您的最后一个测试是唯一需要的测试,但不要忘记初始化checkEmployeePosition
并添加完成:
it("should emit when the button is clicked", done => {
component.checkEmployeePosition = {level: 'dummy'};
component.passVal.subscribe((next: any) => {
expect(next).toEqual(1);
done();
});
btn.nativeElement.click();
});
另一种测试方法是将TestComponent包装在主机组件中,以便为Input() checkEmployeePosition
赋值。
it('should emit when the button is clicked', () => {
let expected;
component.checkEmployeePosition = {level: 'top'};
fixture.detectChanges();
component.passVal.subscribe(data => expected = data);
btn.nativeElement.click();
expect(expected).toEqual({ position: 'top' });
});
或
it('should emit when the button is clicked', () => {
spyOn(component.passVal, 'emit');
component.checkEmployeePosition = {level: 'top'};
fixture.detectChanges();
btn.nativeElement.click();
expect(component.passVal.emit).toHaveBeenCalledWith({ position: 'top' });
});