Skip to content

Commit

Permalink
feat: add typeof assertion (#762)
Browse files Browse the repository at this point in the history
Co-authored-by: Vladimir <sheremet-va@users.noreply.github.com>
  • Loading branch information
Shinigami92 and sheremet-va committed Feb 16, 2022
1 parent 88dcefa commit 5e2324f
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
15 changes: 15 additions & 0 deletions docs/api/index.md
Expand Up @@ -442,6 +442,21 @@ TODO
})
```

### toBeTypeOf

- **Type:** `(c: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined') => Awaitable<void>`

`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<void>`
Expand Down
1 change: 1 addition & 0 deletions packages/vitest/src/index.ts
Expand Up @@ -97,6 +97,7 @@ declare global {
toBeUndefined(): void
toBeNull(): void
toBeDefined(): void
toBeTypeOf(expected: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined'): void
toBeInstanceOf<E>(expected: E): void
toBeCalledTimes(times: number): void
toHaveLength(length: number): void
Expand Down
11 changes: 11 additions & 0 deletions packages/vitest/src/integrations/chai/jest-expect.ts
Expand Up @@ -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)
})
Expand Down
27 changes: 27 additions & 0 deletions test/core/test/jest-expect.test.ts
Expand Up @@ -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')
Expand Down

0 comments on commit 5e2324f

Please sign in to comment.