Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest tests show Object is possibly 'null' errors

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).

like image 555
MsieurKris Avatar asked Sep 10 '25 09:09

MsieurKris


2 Answers

I had this same problem, but wasn't able to use the non-null assertion as in the accepted answer due to having no-non-null-assertion active as well.

Disabling these rules for tests only was also not appealing.

Instead, I added the following function to my test suite:

const assertDefined = <T>(obj: T | null | undefined): T => {
  expect(obj).toBeDefined();
  return obj as T;
}

And updated the tests like so:

let user = await User.findById("id_test");
user = assertDefined(user);
expect(user.password).not.toBe("older_password");
like image 80
meshantz Avatar answered Sep 13 '25 01:09

meshantz


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
  }
}
like image 42
slideshowp2 Avatar answered Sep 13 '25 01:09

slideshowp2