Jest - Externalise 扩展期望匹配器
Posted
技术标签:
【中文标题】Jest - Externalise 扩展期望匹配器【英文标题】:Jest - Externalise extended expect matchers 【发布时间】: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;
【问题讨论】:
【参考方案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。
【讨论】:
以上是关于Jest - Externalise 扩展期望匹配器的主要内容,如果未能解决你的问题,请参考以下文章
用 Jest 测试 TypeScript:“没有重载匹配这个调用”