4

我有一个简单的需求:在 Angular CLI 项目(Angular v6)中的 Jasmine 单元测试中使用我自己的自定义匹配器。几个约束:

  • 我不想修改 node_modules 下的任何内容;这个项目必须能够通过我的构建管道,它每次都进行全新安装。
  • 我不想为了能够添加到typestsconfig.spec.json 中而构建一个 npm 模块。

到目前为止,我能够辨别的是我需要一个 .d.ts 文件,所以这是我的 matchers.d.ts:

/// <reference path="../../../node_modules/@types/jasmine/index.d.ts" />

declare namespace jasmine {
  interface Matchers<T> {
    toContainPath(path: string): boolean;
  }
}

在同一目录中,我有 matchers.ts 文件:

export const customMatchers: jasmine.CustomMatcherFactories  = {

  // Affirms the element contains a sub-element at the given CSS path.
  toContainPath: function (_util, _customEqualityTesters) {
    return {
      compare: function (element: HTMLElement, path: string) {
        const result = {
          pass: false,
          message: ''
        };
        if (!element) {
          result.message = 'Expected element to be non-empty';
        } else if (!path) {
          result.message = 'Expected path to be non-empty';
        } else {
          result.pass = element.querySelector(path) !== null;
          result.message =
            'Expected ' + element + (result.pass ? ' not' : '') + ' to contain ' + path;
        }
        return result;
      }
    };
  }
};

在我的测试(规格)文件中,我有:

import { customMatchers } from 'app/testing/matchers';
. . .
/// <reference path="../../../testing/matchers.d.ts" />
. . .
 beforeEach(() => {
    jasmine.addMatchers(customMatchers);
. . .

最后,我在包含的测试中使用匹配器,例如:

expect(element).toContainPath('my-sidebar');

我还尝试将 matchers.d.ts 的完整路径添加到typestsconfig.spec.json 中的数组中。

唉,我一直无法找到有效的解决方案。失败继续表现为 error TS2339: Property 'toContainPath' does not exist on type 'Matchers<HTMLElement>'

我看了有希望的地方,但无济于事:

  1. 定制茉莉花匹配器
  2. 添加茉莉花匹配器 TypeScript 定义
  3. 茉莉花火柴
  4. 使用自定义匹配器测试 Angular
  5. 手动将输入文件添加到 TypeScript

有人能提供秘方吗?

4

1 回答 1

1

这里的两个答案最终对我有用!

使用 Typescript 创建自定义茉莉花匹配器

在测试文件夹中添加了 index.ts,并使 .ts 和 .d.ts 文件具有不同的名称(例如 custom-matchers.ts 和 matchers-types.d.ts)。

于 2019-01-24T00:05:58.103 回答