Skip to content

Commit eeec501

Browse files
feat(expect): support toBeNullable expect function to check provided value is nullish (#8294)
Co-authored-by: Vladimir <sleuths.slews0s@icloud.com>
1 parent beabefe commit eeec501

File tree

4 files changed

+47
-0
lines changed

4 files changed

+47
-0
lines changed

docs/api/expect.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,32 @@ test('we don\'t have apples', () => {
299299
})
300300
```
301301

302+
## toBeNullable
303+
304+
- **Type:** `() => Awaitable<void>`
305+
306+
`toBeNullable` simply asserts if something is nullable (`null` or `undefined`).
307+
308+
```ts
309+
import { expect, test } from 'vitest'
310+
311+
function apples() {
312+
return null
313+
}
314+
315+
function bananas() {
316+
return null
317+
}
318+
319+
test('we don\'t have apples', () => {
320+
expect(apples()).toBeNullable()
321+
})
322+
323+
test('we don\'t have bananas', () => {
324+
expect(bananas()).toBeNullable()
325+
})
326+
```
327+
302328
## toBeNaN
303329

304330
- **Type:** `() => Awaitable<void>`

packages/expect/src/jest-expect.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,16 @@ export const JestChaiExpect: ChaiPlugin = (chai, utils) => {
405405
obj,
406406
)
407407
})
408+
def('toBeNullable', function () {
409+
const obj = utils.flag(this, 'object')
410+
this.assert(
411+
obj == null,
412+
'expected #{this} to be nullish',
413+
'expected #{this} not to be nullish',
414+
null,
415+
obj,
416+
)
417+
})
408418
def('toBeDefined', function () {
409419
const obj = utils.flag(this, 'object')
410420
this.assert(

packages/expect/src/types.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,14 @@ export interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMa
338338
*/
339339
toBeNull: () => void
340340

341+
/**
342+
* Used to check that a variable is nullable (null or undefined).
343+
*
344+
* @example
345+
* expect(value).toBeNullable();
346+
*/
347+
toBeNullable: () => void
348+
341349
/**
342350
* Ensure that a variable is not undefined.
343351
*

test/core/test/jest-expect.test.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ describe('jest-expect', () => {
3434
expect(1).toBe(1)
3535
expect(null).toBeNull()
3636
expect(1).not.toBeNull()
37+
expect(null).toBeNullable()
38+
expect(undefined).toBeNullable()
39+
expect(0).not.toBeNullable()
3740
expect(null).toBeDefined()
3841
expect(undefined).not.toBeDefined()
3942
expect(undefined).toBeUndefined()

0 commit comments

Comments
 (0)