首页 > 解决方案 > 检查Angular 2单元测试用例中函数返回的对象类型

问题描述

我是编写角度单元测试的新手。我在一个组件中有 2 个方法。

方法一

    canEnableButton(isButtonEnabled: boolean): boolean {
    return isButtonEnabled || !this.isAvailable;
   }

方法二

    getObjectValue(): CustomObject {
    if (!this.canEnableButton(this.limit)) {
        return this.CustomValue;
    }
}

我必须为 getObjectValue() 编写一个测试用例。测试用例应该检查函数是否会返回 CustomObject 或 undefined 类型的对象。

标签: angularjasmineangular-unit-test

解决方案


首先,您需要配置/模拟您的方法中使用的变量。 this.isAvailablethis.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();
  });
  });

推荐阅读