Skip to content

expect(x).toBeTruthy() should properly narrow typescript types to be non-falsy #2883

@NateRadebaugh

Description

@NateRadebaugh

Clear and concise description of the problem

Currently, my tests must look like the following:

const bearerTokenApi1 = new BearerTokenApi(getApiConfig());
let response: GetTokenResponse | undefined;
try {
  response = await bearerTokenApi1.bearerTokenRequestToken({
    requestTokenRequest: {
      userName: env.TOKEN_USERNAME,
      password: env.TOKEN_PASSWORD,
    },
  });
} catch (error: unknown) {
  const errorMessage = await getErrorMessage(error);
  expect(errorMessage).toBe(undefined);
}

// Focus on these lines:
expect(response).toBeTruthy();
invariant(response);

The "invariant" function from tiny-invariant throws when falsy, similar to the .toBeTruthy() but has proper type narrowing.

I believe expect(response).toBeTruthy() should apply some sort of "asserts" to properly type narrow.

Suggested solution

expect(response).toBeTruthy();
invariant(response);

should become

expect(response).toBeTruthy();

Alternative

No response

Additional context

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions