diff --git a/docs/api/index.md b/docs/api/index.md index d30c763c99db..7628342b2431 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -442,6 +442,21 @@ TODO }) ``` +### toBeTypeOf + +- **Type:** `(c: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined') => Awaitable` + + `toBeTypeOf` asserts if an actual value is of type of received type. + + ```ts + import { test, expect } from 'vitest' + const actual = 'stock' + + test('stock is type of string', () => { + expect(actual).toBeTypeOf('string') + }) + ``` + ### toBeInstanceOf - **Type:** `(c: any) => Awaitable` diff --git a/packages/vitest/src/index.ts b/packages/vitest/src/index.ts index ef5c13dd9c49..6507de81a773 100644 --- a/packages/vitest/src/index.ts +++ b/packages/vitest/src/index.ts @@ -97,6 +97,7 @@ declare global { toBeUndefined(): void toBeNull(): void toBeDefined(): void + toBeTypeOf(expected: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined'): void toBeInstanceOf(expected: E): void toBeCalledTimes(times: number): void toHaveLength(length: number): void diff --git a/packages/vitest/src/integrations/chai/jest-expect.ts b/packages/vitest/src/integrations/chai/jest-expect.ts index 488f728f6dfe..58e09ef34254 100644 --- a/packages/vitest/src/integrations/chai/jest-expect.ts +++ b/packages/vitest/src/integrations/chai/jest-expect.ts @@ -227,6 +227,17 @@ export const JestChaiExpect: ChaiPlugin = (chai, utils) => { return this.not.be.undefined }) + def('toBeTypeOf', function(expected: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined') { + const actual = typeof this._obj + const equal = expected === actual + return this.assert( + equal, + 'expected #{this} to be type of #{exp}', + 'expected #{this} not to be type of #{exp}', + expected, + actual, + ) + }) def('toBeInstanceOf', function(obj: any) { return this.instanceOf(obj) }) diff --git a/test/core/test/jest-expect.test.ts b/test/core/test/jest-expect.test.ts index 39e934511c37..3372a907ee1f 100644 --- a/test/core/test/jest-expect.test.ts +++ b/test/core/test/jest-expect.test.ts @@ -310,6 +310,33 @@ describe('.toStrictEqual()', () => { }) }) +describe('toBeTypeOf()', () => { + it.each([ + [1n, 'bigint'], + [true, 'boolean'], + [false, 'boolean'], + [() => {}, 'function'], + [function() {}, 'function'], + [1, 'number'], + [Infinity, 'number'], + [NaN, 'number'], + [0, 'number'], + [{}, 'object'], + [[], 'object'], + [null, 'object'], + ['', 'string'], + ['test', 'string'], + [Symbol('test'), 'symbol'], + [undefined, 'undefined'], + ] as const)('pass with typeof %s === %s', (actual, expected) => { + expect(actual).toBeTypeOf(expected) + }) + + it('pass with negotiation', () => { + expect('test').not.toBeTypeOf('number') + }) +}) + describe('async expect', () => { it('resolves', async() => { await expect((async() => 'true')()).resolves.toBe('true')