首页 > 解决方案 > 导入的库 - 模拟方法和排除

问题描述

我有一个组件,我在其中使用create()来自外部库(Zoid)的方法。我正在尝试模拟 this 方法,但如果没有属于对象的方法,我不知道该怎么做。此外,我从 Zoid 库中得到了一些 JS 错误,但在我的单元测试中,我根本不想导入该库。任何帮助将非常感激。

我的组件的相关部分:

import { create } from 'zoid/dist/zoid';

ngOnInit() {
  // Initialize the zoid instance
  this.widgetInstance = zoid.create({
    tag: 'payment-widget',
    url: this.iframeSrc,
    dimensions: {
      width: '100%',
      height: '600px',
    }
  });
}

这是我的单元测试

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PaymentWidgetComponent } from './payment-widget.component';

const zoid = {
  create: () => {
    return {};
  }
};   

describe('PaymentWidgetComponent', () => {
  let component: PaymentWidgetComponent;
  let fixture: ComponentFixture<PaymentWidgetComponent>;
  const mockWidgetInstance = jasmine.createSpyObj('WidgetInstance', ['render']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [PaymentWidgetComponent]
    })
      .compileComponents();
  }));   

  beforeEach(() => {
    fixture = TestBed.createComponent(PaymentWidgetComponent);
    component = fixture.componentInstance;
    component.widgetInstance = mockWidgetInstance;
    fixture.detectChanges();
  });   

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});

标签: angularjasmine

解决方案


我认为您也必须将其导入到您的单元测试文件中。

尝试这个:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PaymentWidgetComponent } from './payment-widget.component';
import * as zoid from 'zoid/dist/zoid'; // import everything like so
 

describe('PaymentWidgetComponent', () => {
  let component: PaymentWidgetComponent;
  let fixture: ComponentFixture<PaymentWidgetComponent>;
  const mockWidgetInstance = jasmine.createSpyObj('WidgetInstance', ['render']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [PaymentWidgetComponent]
    })
      .compileComponents();
  }));   

  beforeEach(() => {
    fixture = TestBed.createComponent(PaymentWidgetComponent);
    component = fixture.componentInstance;
    spyOn(zoid, 'create'); // spy on zoid.create and make it return undefined
    component.widgetInstance = mockWidgetInstance; // you're mocking widgetInstance here so it should be fine.
    fixture.detectChanges();
  });   

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});

推荐阅读