【问题标题】: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 类型的对象。

【问题讨论】:

  • 欢迎来到 StackOverflow!请阅读how to write a good question。搜索如何做你想做的事,尝试编写代码,如果遇到问题,在这里发布你的代码和准确的问题。

标签: angular jasmine angular-unit-test


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多