Angular Unit Test (w Jest) 一个导入并使用esm模块的服务。

问题描述 投票:0回答:1

Explination

我有一个单元测试问题,使用Angular (v 9)、Jest (24.9.0)和一个ECMAScript模块(dialog-polyfill (v 0.5.1) )。这个polyfill增加了对 HTMLDialogElement. 问题是,它有一个方法 registerDialog 当对话框在DOM中时需要被调用。它把对话框元素作为唯一的参数。我创建的这个服务,注册了对话框并将其添加到一个数组中。所有的实现都能完美地工作,但是测试失败了,因为它不知道polyfill是什么。我一直得到以下错误。

TypeError: 不能读取未定义的属性'registerDialog'。

  • 注意:我对Angular的测试比较陌生,我的实现可能不正确,如果正确,请告诉我。
  • 第二点:我不知道除了调用 "Dialog Element "之外,是否还有更好的方法来创建Dialog Element。createElement 在Jest测试中的文档上。

对话服务

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

import dialogPolyfill from 'dialog-polyfill';

@Injectable({
  providedIn: 'root'
})
export class DialogService {
  public dialogs$: BehaviorSubject<HTMLDialogElement[]> = new BehaviorSubject<
    HTMLDialogElement[]
  >([]);

  private dialogs: [] = [];

  constructor() {}

  register(dialog: HTMLDialogElement) {
    dialogPolyfill.registerDialog(dialog);
    this.dialogs$.next([...this.dialogs, dialog]);
  }
}

对话服务规格

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

import { DialogService } from './dialog.service';

describe('DialogService', () => {
  let service: DialogService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(DialogService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should register a dialog', () => {
    expect(service.dialogs$.getValue().length).toBe(0);
    service.register(document.createElement('dialog'));
    expect(service.dialogs$.getValue().length).toBe(1);
  });
});

参考文献

javascript angular jestjs
1个回答
1
投票

你需要在你的TestBed中提供你的服务。

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [DialogService] 
  });
  service = TestBed.inject(DialogService);
});
© www.soinside.com 2019 - 2024. All rights reserved.