【问题标题】:Check type of object returned from function in Angular 2 Unit Test Case检查Angular 2单元测试用例中函数返回的对象类型
【发布时间】:2021-10-06 06:18:31
【问题描述】:
我是编写角度单元测试的新手。我在一个组件中有 2 个方法。
方法一
canEnableButton(isButtonEnabled: boolean): boolean {
return isButtonEnabled || !this.isAvailable;
}
方法二
getObjectValue(): CustomObject {
if (!this.canEnableButton(this.limit)) {
return this.CustomValue;
}
}
我必须为 getObjectValue() 编写一个测试用例。测试用例应该检查函数是否会返回 CustomObject 或 undefined 类型的对象。
【问题讨论】:
标签:
angular
jasmine
angular-unit-test
【解决方案1】:
首先,您需要配置/模拟您的方法中使用的变量。
this.isAvailable 和 this.limit。由于测试的结果取决于他们。
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestComponent]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should return CustomObject', () => {
component.limit = false;
component.isAvailable = true;
component.customValue = {} as CustomObject; // you need to mock customValue related to your CustomObject
expect(component.getObjectValue()).toEqual(component.customValue);
});
it('should return undefined', () => {
component.limit = true;
component.isAvailable = true;
component.customValue = {} as CustomObject; // you need to mock customValue related to your CustomObject
expect(component.getObjectValue()).toBeUndefined();
});
});