Eol*_*ley 6 testing node.js typescript jestjs ts-jest
我有。node.js-TypeScript 应用程序和 Jest 用于测试。使用此参考https://jestjs.io/docs/expect#expecttextendmatchers我的测试类中有一些扩展的期望匹配器。就像下面的例子一样。我在几个不同的测试类中有很多共同的扩展。有没有办法外部化/分组这些扩展匹配器并通过导入它们在测试类中使用?
例子:
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();
});
Run Code Online (Sandbox Code Playgroud)
我的笑话.d.ts:
export {};
declare global {
namespace jest {
interface Matchers<R> {
hasTestData(): R;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 2
对于常见的扩展期望,我使用以下逻辑;
扩展期望.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,
};
}
}
Run Code Online (Sandbox Code Playgroud)
定义了常用方法,现在如何使用它;
你的测试类看起来像,
import { toBeDivisibleByExternalValue } from "../ExtendedExpects";
expect.extend({
toBeDivisibleByExternalValue
});
test('is divisible by external value', async () => {
await expect(100).toBeDivisibleByExternalValue();
await expect(101).not.toBeDivisibleByExternalValue();
});
Run Code Online (Sandbox Code Playgroud)
您不再需要 jest.d.ts。
归档时间: |
|
查看次数: |
1445 次 |
最近记录: |