typescriptjestjsts-jest

How can I make TypeScript null check follow Jest expect response?


I am using Jest as unit test framework for TypeScript code. Below is the code:

const result: User|null = getResult();
expect(result).not.toBeNull();
expect(result.name).toBe('Joey');  // typescript compiles `result` could be null here.

The result can be either User type or null. But the next expect already ensure it is not null. But TypeScript still complains about the last statement. Is there a way to let TypeScript respect Jest expect?


Solution

  • You can use the non-null assertion operator (!) to tell TypeScript that a value is not null. For example:

    const result: User|null = getResult();
    expect(result).not.toBeNull();
    expect(result!.name).toBe('Joey');
    

    Or you could also add an additional check to make sure that result is not null before accessing its name property like:

    const result: User|null = getResult();
    expect(result).not.toBeNull();
    if (result) {
      expect(result.name).toBe('Joey');
    }