【问题标题】:How to add types checker for the Jest in the TypeScript app?如何在 TypeScript 应用程序中为 Jest 添加类型检查器?
【发布时间】:2020-01-03 11:44:46
【问题描述】:

我需要在 Jest 中添加一些类型检查器。它一定看起来像expect(someVar).toBeType('string')expect(someVar).toBeType(['string', 'object'])

我尝试添加一些 checker-helper,但看起来有点难看。

const toBeType = (arg:any, type:string) => {
    const argType = typeof arg;

    if (argType !== type)
        throw new Error(`Expected '${type}' but got '${argType}' for the '${arg}'.`);
};

我想向jest 命名空间添加类似的功能,以便能够调用类型检查器,如expect(someVar).toBeType('boolean')

【问题讨论】:

  • 编译器(假设您的测试也在 typescript 中并由 ts-jest 运行)将强制执行类型安全,无需添加断言。

标签: javascript unit-testing testing automated-tests jestjs


【解决方案1】:

我通过这种方式解决了这个问题。要向 Jest 添加功能,我们应该使用 expect.extend({...})。因此,要将 toBeType 方法添加到 Jest,我们应该将此代码写入某个 setupTests.js 文件:

// setupTests.js

expect.extend({
    /**
     * @param {*} received
     * @param {string|string[]} arg
     * @return {{pass:boolean,message:(function():string)}}
     */
    toBeType(received, arg) {
        const isCorrectType = arg => {
            const receivedType = typeof received;

            const checkForSingle = arg => {
                const type = receivedType === 'object'
                    ? Array.isArray(received)
                        ? 'array'
                        : receivedType
                    : receivedType;

                return type === arg;
            };

            const checkForArr = arg => {
                const reducer = (prev, curr) => prev
                    || isCorrectType(curr).isCorrect;

                return arg.reduce(reducer, false);
            };

            return {
                receivedType,
                isCorrect: Array.isArray(arg)
                    ? checkForArr(arg)
                    : checkForSingle(arg)
            };
        };

        const {isCorrect, receivedType} = isCorrectType(arg);

        return {
            pass: isCorrect,
            message: () => {
                const toBe = Array.isArray(arg)
                    ? arg.join(`' or '`)
                    : arg;

                return `Expected '${received}' of '${receivedType}' type to be of '${toBe}' type(s)`;
            }
        };
    }
});

不要忘记将setupTests.js 添加到jest.config.js 文件中,如下所示:

// jest.config.js

module.exports = {
    ...your_configurations...
    setupFilesAfterEnv: ['<rootDir>/setupTests.js'],
};

此外,我们还必须扩展 global.d.ts 文件来表示解释器,我们在 extend 命名空间中有 toBeType 方法(如果只有您使用 TypeScript,则它是必需的)。这是我们必须添加到global.d.ts的代码:

// global.d.ts

declare namespace jest {
    interface Matchers<R> {
        toBeType(type:string|string[]);
    }
}

这段代码说:获取jest命名空间并使用toBeType方法扩展Matchers&lt;R&gt;接口。 (可以在@types/jest节点模块查看Matchers&lt;R&gt;接口实现。)

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 2021-08-29
    • 1970-01-01
    • 2019-01-25
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2021-08-03
    相关资源
    最近更新 更多