简体   繁体   English

如何在单元测试中模拟 TS 类

[英]How to mock TS class in unit tests

Consider the following code snippet:考虑以下代码片段:

import {Calendar} from '@fullcalendar/core';

...

ngAfterViewInit() {
  this.calendar = new Calendar(this.element.nativeElement, config);
  this.calendar.render();
}

I'm using fullcalendar plugin but it has nothing to do with my original question, I think, it might be any other dependency.我正在使用 fullcalendar 插件,但它与我原来的问题无关,我认为,它可能是任何其他依赖项。 So the plugin creates a calendar view.所以插件创建了一个日历视图。 It is up to fullcalendar team to test the calendar behavior, while I'm responsible to test the calendar integration.由 fullcalendar 团队来测试日历行为,而我负责测试日历集成。 So I need to test that the calendar has been initialized with correct config, therefore I want to omit real constructor and retrieve params.所以我需要测试日历是否已使用正确的配置初始化,因此我想省略真正的构造函数并检索参数。 And also I don't want to create an instance of the calendar.而且我不想创建日历的实例。

How to mock Calendar class in my tests?如何在我的测试中模拟Calendar类?

It is good practice to wrap your library calls.包装您的库调用是一种很好的做法。 First of all it's easier to test them and if the library interface will change you only have to change your code at a single location and keep your own interface in the rest of your code.首先,测试它们更容易,如果库接口会发生变化,您只需在一个位置更改代码,并在其余代码中保留您自己的接口。

Therefore one solution for your problem would be to wrap the calendar creation in a factory service like:因此,您的问题的一种解决方案是将日历创建包装在工厂服务中,例如:

@Injectable({providedIn:'root'})
export class FullcalendarFactoryService{

  public buildCalendar(element:HTMLElement,config:any){
    return new Calendar(element,config);
  }
}

In your component you have to inject your factory service and use it like:在你的组件中,你必须注入你的工厂服务并像这样使用它:

constructor(public calenderFactory:FullcalendarFactoryService) {
}

ngAfterViewInit(): void {
    this.calendar = this.calenderFactory.buildCalendar(this.element.nativeElement,this.config);
    this.calendar.render();
}

And to test, you could simply mock your factory function like shown below:为了测试,你可以简单地模拟你的工厂函数,如下所示:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        YourComponent
      ],
      providers: [{
        provide: FullcalendarFactoryService,
        useClass: class {
          buildCalendar = jasmine.createSpy('buildCalendar').and.returnValue({
            render: () => true
          });
        }
      }
      ]
    }).compileComponents();

    calendarFactory = TestBed.get(FullcalendarFactoryService);

}));

it('should call factory method with element and config', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();

    expect(calendarFactory.buildCalendar).toHaveBeenCalledWith(fixture.componentInstance.element.nativeElement, fixture.componentInstance.config);
  });

UPDATE:更新:

To test if the services buildCalendar function returns an instance of Calendar you would test your service like shown below:要测试服务buildCalendar函数是否返回Calendar一个实例,您将测试您的服务,如下所示:

import {FullcalendarFactoryService} from './fullcalendar-factory.service';
import {Calendar} from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid'

describe('calendar factory service', () => {
  let factory:FullcalendarFactoryService;

  beforeEach(() => {
    factory = new FullcalendarFactoryService();
  })

  it('should return calender instance',() => {
    expect(factory.buildCalendar(document.createElement('test'),{plugins:[dayGridPlugin]})).toEqual(jasmine.any(Calendar))
  })
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在自定义表单控件中模拟 ngControl - Angular 单元测试 - How to mock ngControl in Custom Form Control - Unit tests Angular 用玩笑编写单元测试时如何模拟formik useFormikContext钩子 - How to mock the formik useFormikContext hook when writing unit tests with jest 如何在nestjs单元测试中模拟nest-winston logger依赖 - How to mock a nest-winston logger dependency in nestjs unit tests 如何在 ts-mock 中模拟导入的 function - How to mock imported function in ts-mock Angular 6单元测试:如何使用test.ts进行业力测试 - Angular 6 Unit testing : how to use test.ts for running karma tests 如何在打字稿的单元测试中模拟类中的硬私有属性 - how to mock hard private property in class in unit test in typescript 如何模拟使用ts Mockito在Typescript中的另一个类中初始化的类方法? - How to mock a class method's which is initialized inside another class in typescript using ts mockito? 如何在 React Native 中使用 TypeScript 为单元测试模拟 React Navigation 的导航道具? - How to mock React Navigation's navigation prop for unit tests with TypeScript in React Native? 如何在茉莉花单元测试中为角离子电容器插件添加正确的模拟逻辑 - How to add correct mock logic for angular ionic capacitor plugins on jasmine unit-tests 如何在笑话单元测试中模拟私有 ngxs state 服务依赖/属性 - How to mock private ngxs state service dependency/property in jest unit tests
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM