jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.06k stars 6.44k forks source link

Add support for TypeScript's Assertion Functions #9146

Closed swashcap closed 4 years ago

swashcap commented 4 years ago

šŸš€ 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.

SimenB commented 4 years ago

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

hjr3 commented 4 years ago

I made an issue here: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/41179

github-actions[bot] commented 3 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.