Support TypeScript 3.7's new assertion functions.
Jest should support this TypeScript language feature to make authoring tests simpler.
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.)
Why does this feature belong in the Jest core platform?
This feature request relates to assertions, which are at the core of Jest.
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
I made an issue here: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/41179
Most helpful comment
I made an issue here: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/41179