Jest tests show Object is possibly 'null' errors

Viewed 2598

I have some tests cases which are testing mongoose Models. But on running them with Jest (typescript code) I get many running errors :

error TS2531: Object is possibly 'null'.

Example code (error is on line 3) :

const user = await User.findById("id_test");
expect(user).toBeDefined();
expect(user.password).not.toBe("older_password");

Yes my user can be null, but it can be a unprecise test case but certainly not a blocking error...

How can I make my test pass ? (Weither precising my test, weither silencing this type of error BUT I don't want to silence this error for the whole project, I want to silence only on tests file, not on src files).

2 Answers

Option 1. You can use Non-null assertion operator to assert that user is not null.

E.g.

user.ts:

import mongoose from 'mongoose';
const { Schema } = mongoose;

export interface IUser extends mongoose.Document {
  id_test: string;
  password: string;
}

const UserSchema = new Schema({
  id_test: String,
  password: String,
});

const User = mongoose.model<IUser>('User', UserSchema);

export { User };

user.test.ts:

import { User } from './user';

describe('65148503', () => {
  it('should pass', async () => {
    const user = await User.findById('id_test');
    expect(user).toBeDefined();
    expect(user!.password).not.toBe('older_password'); 
  });
});

Option 2. Using Option 1, you will use a lot of ! operators in test cases, if you find it very cumbersome, you can create tsconfig.json for the src directory with --strictnullchecks: true, create tsconfig.json for test directory with --strictnullchecks: false. More info, see --strictnullchecks

E.g.

tsconfig.json in the test directory:

{
  "extends": "../../../tsconfig.json",
  "compilerOptions": {
    "strictPropertyInitialization": false,
    "strictNullChecks": false
  }
}

but like, aint you testing ? do not complicate.

import { User } from './user';

describe('65148503', () => {
  it('should pass', async () => {
    const user = await User.findById('id_test');
    // if user is null end the test.
    if (!user) {
      throw new Error("User is null");
    }
    // typescript wont b*ch about that any mow!
    expect(user).toBeDefined();
    expect(user!.password).not.toBe('older_password'); 
  });
});
Related