简体   繁体   English

如何在TypeScript应用程序中为Jest添加类型检查器?

[英]How to add types checker for the Jest in the TypeScript app?

I need to add some type checker to the Jest. 我需要在Jest中添加一些类型检查器。 It must look somehow like expect(someVar).toBeType('string') and expect(someVar).toBeType(['string', 'object']) . 它必须看起来像expect(someVar).toBeType('string')expect(someVar).toBeType(['string', 'object'])

I tried to add some checker-helper, but it looks a little bit ugly. 我试图添加一些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}'.`);
};

I want to add similar functionality to the jest namespace to have ability to call type checker like expect(someVar).toBeType('boolean') . 我想向jest名称空间添加类似的功能,以便能够调用类型检查器,例如expect(someVar).toBeType('boolean')

You can use check type similar javascript 您可以使用类似javascript的检查类型

You can test code below: 您可以在下面测试代码:

if (argType !== type)

I resolved this problem this way. 我这样解决了这个问题。 To add functionality to the Jest we should use expect.extend({...}) . 为了向Jest添加功能,我们应该使用expect.extend({...}) So, to add toBeType method to the Jest we should write this code to some setupTests.js file: 因此,要将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)`;
            }
        };
    }
});

Don't forget to add setupTests.js to the jest.config.js file as follows: 不要忘记将setupTests.js添加到jest.config.js文件,如下所示:

// jest.config.js

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

Also we have to extend global.d.ts file to say interpreter we have toBeType method at the extend namespace (it is required if only you are using TypeScript). 此外,我们还必须扩展global.d.ts文件以说明解释器,在extend名称空间中必须具有toBeType方法(仅在使用TypeScript时才需要)。 Here is code we have to add to global.d.ts : 这是我们必须添加到global.d.ts代码:

// global.d.ts

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

This code says: get jest namespace and extend Matchers<R> interface with the toBeType method. 这段代码说:获取jest名称空间,并使用toBeType方法扩展toBeType Matchers<R>接口。 (You can look at Matchers<R> interface implementation at the @types/jest node module.) (您可以在@types/jest节点模块上查看Matchers<R>接口的实现。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM