简体   繁体   English

如何使用 jest js 在 Angular 中 createSpyObj?

[英]How to createSpyObj in Angular using jest js?

I am using jest for Angular testing.我正在使用 jest 进行 Angular 测试。

In my scenario I have to test child component from parent.在我的场景中,我必须从父级测试子组件。 here I am accessing child component methods and properties using @viewchild in parent componet在这里,我在父组件中使用 @viewchild 访问子组件方法和属性

import { Component } from '@angular/core';

    @Component({
        template: `<div><\div>`
    })
    export class ChildComponent {
    
        public childMethod() {
            ...
        }
    }


import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from 'child.component';

@Component({
    template: ``
})
export class ParentComponent {

    @ViewChild('child')
    public child: ChildComponent;

    public parentMethod() {
        this.child.childMethod();
    }
}

In jasmin we can do using createspyobj在 jasmin 中,我们可以使用 createpyobj

jasmin茉莉花

const childComponent = jasmine.createSpyObj('ChildComponent', ['childMethod']);
it('should invoke childMethod when parentMethod is invoked', () => {
        component.childComponent =  childComponent;
        component.parentMethod();
        expect(childComponent.childMethod).toHaveBeenCalled();
    });

(exactly I want this How to to same in jest . I did not find anything . How to spy child component (正是我想要这个如何在玩笑中相同。我没有找到任何东西。如何监视子组件

Can any one please tell.有哪位可以告诉一下。

Thanks in advance提前致谢

Jest doesn't have this utility function. Jest 没有这个效用函数。 It needs to be written manually, also this way it can provide type safety if needed that Jasmine createSpyObj can't have by design:它需要手动编写,这样它也可以在需要时提供类型安全性,而 Jasmine createSpyObj在设计上无法提供:

const mockChildComponent: ChildComponent = {
  childMethod: jest.fn(...)
}

There are auto-mock features to provide dummy mock objects for existing modules that provide the same functionality, although this may give unexpected results because of undocumented magic behind them:有一些自动模拟功能可以为提供相同功能的现有模块提供虚拟模拟对象,尽管这可能会由于它们背后未记录的魔法而产生意想不到的结果:

const { ChildComponent: MockChildComponent } = jest.createMockFromModule('child.component')
mockChildComponent = new MockChildComponent()

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM