首页 > 解决方案 > 无法使用打字稿和角度为 Jasmine 添加自定义匹配器

问题描述

我正在尝试向 jasmine 添加多个新的自定义匹配器并使用它,目标是创建一个注册 2 个匹配器的文件,并且所有匹配器必须可用于每个测试文件,只需一次注册。

所以我有一个名为custom-matchers.ts

/// <reference path="custom-matchers.d.ts"/>

(() => {
  beforeEach(() => {
    jasmine.addMatchers({
      toHaveText: () => {
        return {
          compare: (actual, expected) => {
            return {
              pass: actual.getText().then(pass => pass === expected)
            };
          },
        };
      },
      toBePresent: () => {
        return {
          compare: (actual, expected) => {
            return {
              pass: actual.isPresent().then(pass => pass === expected),
            };
          },
        };
      }
    });
  });
})();

一个名为的类型定义文件custom-matchers.d.ts(我尝试使用与引用文件不同的名称,但它是相同的):

declare namespace jasmine {
  interface Matchers<T> {
    toHaveText(text: any): boolean;
    toBePresent(text: any): boolean;
  }
}

该文件在另一个名为 e2e-helper 的文件中注册,该文件在每个测试文件中导入e2e-helper.ts

/// <reference path="custom-matchers.d.ts"/>
import './custom-matchers';

例如,当我尝试在测试文件中使用它时:

expect(object as any).toBePresent();

我收到一个错误:

“匹配器”类型上不存在属性“toBePresent”

标签: angulartypescripttestingjasmineprotractor

解决方案


我找到了一个解决方案,我只是在文件下方的帮助文件中导入我的定义文件custom-matchers.ts并将其重命名为具有不同的名称导入,所以我有:

import './custom-matchers';
import './custom-matchers-types'; // definition file

推荐阅读