BobJenkins773770
BobJenkins773770

Reputation: 1

Imported library - mock method and exclude

I have a component where I use a method, create() from an outside library (Zoid). I'm trying to mock the this method but I'm not sure how to do it without having the method belonging to an object. Also, I'm getting some JS errors from the Zoid library but in my unit test I don't want to have the library imported at all. Any help would be much appreciated.

Relevant part of my component:

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',
    }
  });
}

Here is my unit test

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();
  });

});

Upvotes: 0

Views: 234

Answers (1)

AliF50
AliF50

Reputation: 18849

I think you have to import it into your unit test file as well.

Try this:

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();
  });

});

Upvotes: 1

Related Questions