【问题标题】:Jest - Externalise extended expect matchersJest - Externalise 扩展期望匹配器
【发布时间】:2021-06-12 10:50:13
【问题描述】:

我有。 node.js-TypeScript applciation 和 Jest 用于测试。使用这个参考https://jestjs.io/docs/expect#expectextendmatchers 我的测试类中有一些扩展的期望匹配器。就像下面的例子一样。我在几个不同的测试类中有很多常见的扩展。有没有办法将这些扩展匹配器外部化/分组并通过导入它们在测试类中使用?

例子:

expect.extend({
  async toBeDivisibleByExternalValue(received) {
    const externalValue = await getExternalValueFromRemoteSource();
    const pass = received % externalValue == 0;
    if (pass) {
      return {
        message: () =>
          `expected ${received} not to be divisible by ${externalValue}`,
        pass: true,
      };
    } else {
      return {
        message: () =>
          `expected ${received} to be divisible by ${externalValue}`,
        pass: false,
      };
    }
  },
});

test('is divisible by external value', async () => {
  await expect(100).toBeDivisibleByExternalValue();
  await expect(101).not.toBeDivisibleByExternalValue();
});

我的笑话.d.ts:

export {};
declare global {
  namespace jest {
    interface Matchers<R> {
      hasTestData(): R;
    }
}

【问题讨论】:

    标签: node.js typescript testing jestjs ts-jest


    【解决方案1】:

    对于常见的扩展期望,我使用以下逻辑;

    ExtendedExpects.ts:

    declare global {
        namespace jest {
            interface Matchers<R> {
                toBeDivisibleByExternalValue(): R;
            }
        }
    }
    export function toBeDivisibleByExternalValue(received:any): jest.CustomMatcherResult {
        const externalValue = await getExternalValueFromRemoteSource();
        const pass = received % externalValue == 0;
        if (pass) {
          return {
            message: () =>
              `expected ${received} not to be divisible by ${externalValue}`,
            pass: true,
          };
        } else {
          return {
            message: () =>
              `expected ${received} to be divisible by ${externalValue}`,
            pass: false,
          };
        }
    }
    

    你定义了通用方法,现在如何使用它;

    你的测试类看起来像,

    import { toBeDivisibleByExternalValue } from "../ExtendedExpects";
    
    expect.extend({
       toBeDivisibleByExternalValue
    });
    
    test('is divisible by external value', async () => {
      await expect(100).toBeDivisibleByExternalValue();
      await expect(101).not.toBeDivisibleByExternalValue();
    });
    

    你不再需要 jest.d.ts。

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 2017-05-02
      • 2014-11-06
      相关资源
      最近更新 更多