angular - 导入的库 - 模拟方法和排除
问题描述
我有一个组件,我在其中使用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();
});
});
解决方案
我认为您也必须将其导入到您的单元测试文件中。
尝试这个:
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();
});
});
推荐阅读
- java - 如果我错误地从 java 项目中删除了 sdk 文件怎么办
- javascript - 游标_id的mongoDB分页不起作用
- karate - 空手道:如果匹配条件包含深度,如何添加
- aws-cdk - AWS CDK 按特定顺序跨账户部署堆栈
- javascript - 您如何将 awaitMessages 与mentions.users.first 一起使用?
- azure - azurerm_public_ip 中是否支持 IpTag
- javascript - 如何在nodejs中获取php array_multisort函数等效输出
- php - 修复模型颤振/飞镖
- wordpress - wordpress 上的多个元条件
- bash - 如何在不更改脚本的情况下在 bash 脚本中使用别名?