最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add types checker for the Jest in the TypeScript app? - Stack Overflow

programmeradmin0浏览0评论

I need to add some type checker to the Jest. It must look somehow like expect(someVar).toBeType('string') and expect(someVar).toBeType(['string', 'object']).

I tried to add some checker-helper, but it looks a little bit ugly.

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').

I need to add some type checker to the Jest. It must look somehow like expect(someVar).toBeType('string') and expect(someVar).toBeType(['string', 'object']).

I tried to add some checker-helper, but it looks a little bit ugly.

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').

Share Improve this question edited Aug 30, 2019 at 8:29 B. Bohdan asked Aug 30, 2019 at 8:14 B. BohdanB. Bohdan 5295 silver badges13 bronze badges 1
  • The piler (assuming your tests are in typescript too and run by ts-jest) will enforce type safety, no need to add assertions. – Jared Smith Commented Aug 30, 2019 at 8:28
Add a ment  | 

1 Answer 1

Reset to default 4

I resolved this problem this way. To add functionality to the Jest we should use expect.extend({...}). So, to add toBeType method to the Jest we should write this code to some setupTests.js file:

// 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:

// 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). Here is code we have to add to 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. (You can look at Matchers<R> interface implementation at the @types/jest node module.)

发布评论

评论列表(0)

  1. 暂无评论