angular - 在 Angular CLI 项目中使用 Jasmine 自定义匹配器

标签 angular typescript unit-testing jasmine jasmine-matchers

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

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

到目前为止,我已经能够辨别出我需要一个 .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 的完整路径添加到 tsconfig.spec.json 中的 types 数组。

唉,我没能找到有效的解决方案。失败继续表现为 ojit_代码

我看过的有前途的地方,但无济于事:

  1. custom jasmine matchers
  2. adding a jasmine matcher TypeScript definition
  3. jasmine matchers
  4. testing Angular with custom matchers
  5. manually add typing file to TypeScript

谁能提供秘方?

最佳答案

这里的两个答案结合在一起最终对我有用!

Create custom jasmine matcher using Typescript

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

关于angular - 在 Angular CLI 项目中使用 Jasmine 自定义匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54282597/

相关文章:

javascript - 如何找到数组对象中的近距离,并选择近距离并提取对象

Python帮助无法弄清楚单元测试失败的原因

PHPUnit 错误调用模拟上的未定义方法

objective-c - 如何使用 OCMock 正确测试此方法?

javascript - Angular:在FormGroup中定义默认值输入FormField

angular - ASPNETZERO - 来自 Angular 4/.Net Core 的 SelectPdf ConvertUrl() 中的身份验证

typescript - TypeScript 中的多个可选参数

angular - 如何在 Angular 中有条件地编译特定于环境的模板

javascript - Angular2 - 如何使用 OR 语句?

css - gulp + webpack + css-loader + typescript : "cannot find module"