Jest: Add support for TypeScript's Assertion Functions

Created on 7 Nov 2019  路  2Comments  路  Source: facebook/jest

馃殌 Feature Proposal

Support TypeScript 3.7's new assertion functions.

Motivation

Jest should support this TypeScript language feature to make authoring tests simpler.

Example

Let's say I have a function under test that returns a nullable value:

export interface Data {
  anotherCoolProp: any
  somethingNeat: any
}

export function gimmeData(): Data | null {
  // Implementation details
  // ...
}

Currently, testing the results requires null checks for every assertion:

test('gimme that data', () => {
  const data = gimmeData()

  expect(data).toBeTruthy()

  expect(data!.anotherCoolProp).toEqual('coolio')
  expect(data!.somethingNeat).toEqual('neato')
})

// or:
test('gimme that data', () => {
  const data = gimmeData()

  if (!data) {
    throw new Error('Expected data to be non-null')
  }

  expect(data.anotherCoolProp).toEqual('coolio')
  expect(data.somethingNeat).toEqual('neato')
})

The first uses the ! non-null operator, which opts out of type safety and can lead to confusing error reports. The second seems non-idiomatic: why not write expect(data).toBeTruthy()?

With TypeScript 3.7 you can now define Jest's global expect to behave this way:

declare function <T>expect(value: T): asserts value is NonNullable<T>

(Although typing w/ the Jest's chaining will be a bit more involved.)

Pitch

Why does this feature belong in the Jest core platform?

This feature request relates to assertions, which are at the core of Jest.

Feature Request

Most helpful comment

All 2 comments

The types are not maintained in this repo (yet, at least) - this issue belongs in DefinitelyTyped.

I do agree it'd be nice, though! Please add a link in this issue when you create one over there

Was this page helpful?
0 / 5 - 0 ratings