Jest.js 模拟独立组件中的独立指令

bxjv4tth  于 2022-12-20  发布在  Jest
关注(0)|答案(1)|浏览(189)

我尝试为一个独立组件编写一个单元测试,并模拟它的依赖关系。这个独立组件包含以下内容:

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DemoDirectiveDirective } from './demo-directive.directive';

@Component({
  selector: 'app-demo-cmp',
  standalone: true,
  imports: [CommonModule,DemoDirectiveDirective],
  templateUrl: './demo-cmp.component.html',
})
export class DemoCmpComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {}
}

并且DemoDirectiveDirective包含以下内容:

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appDemoDirective]',
  standalone: true,
})
export class DemoDirectiveDirective {
  constructor(private hostElement: ElementRef) {
    this.hostElement.nativeElement.innerHTML += 'Update from directive! ';
  }
}

我想像这样测试DemoCmpComponent

import { ComponentFixture, TestBed } from '@angular/core/testing';

import { DemoCmpComponent } from './demo-cmp.component';

describe('DemoCmpComponent', () => {

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [DemoCmpComponent],
    }).compileComponents();
  });

  it('should create', () => {
    const fixture = TestBed.createComponent(DemoCmpComponent);
    fixture.detectChanges();

    expect(fixture.nativeElement.querySelector('p').innerHTML).toBe(
      'demo-cmp works!'
    );
  });
});

由于p标签的内容为Update from directive! demo-cmp works!,因此本测试将失败。
我这里缺少的是模拟DemoDirectiveDirective的步骤,我不知道如何模拟,而且我在Angular页面上找不到任何相关资源。
注意,这只是一个演示测试,一个概念验证。请忽略组件名称和多余的测试。
下面是包含代码的GitHub存储库。

vawmfj5a

vawmfj5a1#

模拟Angular 声明最简单的方法之一是使用模拟库,例如ng-mocks
ng-mocks支持独立组件,它的MockBuilder知道如何模拟独立声明的导入。
在您的情况下,测试可能类似于:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MockBuilder } from "ng-mocks";

import { DemoCmpComponent } from './demo-cmp.component';

describe('DemoCmpComponent', () => {

  beforeEach(() => {
    return MockBuilder(DemoCmpComponent);
    // it will mock DemoDirectiveDirective automatically,
    // because it's a dependency of DemoCmpComponent.
  });

  it('should create', () => {
    const fixture = TestBed.createComponent(DemoCmpComponent);
    fixture.detectChanges();

    expect(fixture.nativeElement.querySelector('p').innerHTML).toBe(
      'demo-cmp works!'
    );
  });
});

下面是一个活生生的例子:https://codesandbox.io/s/bold-kate-1gkymd?file=/src/test.spec.ts:770-812

相关问题