首页 > 解决方案 > jasmine callFake 未被使用;真正的函数仍然被调用

问题描述

我正在尝试使用 spyOn 和 callFake 来模拟函数调用,但仍在调用真正的函数而不是假函数。

组件代码:

async getOrderProfile() {
    let ordersSuccess = false;
    ...
    try {
      const ordersResponse = await this.ordersService.getOrderProfile(params);      
      ordersSuccess = this.validateResponse(ordersResponse);
       ...
    } catch (error) {
       ...
    }

  }

规格:

describe('OrdersComponent', () => {
  let component: OrdersComponent;
  let fixture: ComponentFixture<OrdersComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [OrdersComponent],
      imports: [],
      providers: []
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(OrdersComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should call getOrdersNoteData', () => {
    ...
    spyOn(component, 'validateResponse').and.callFake(() => {
      console.log('faked method');
      return true;
    });
    component.getOrderProfile();
    ...
  });
});

我没有看到我的测试语句记录到控制台,真正的函数抛出错误,因为它没有所有预期的数据。我不确定我在这方面做错了什么。

我也没有运气使用过 spyOn returnValue:

spyOn(component, 'validateResponse').and.returnValue(true)

标签: angularjasmine

解决方案


推荐阅读