Search code examples
nestjsts-jest

Jest fails to pass throw new error with framework nestjs


Here's an example of how I make the test get to the error line.

I've tried several ways that I found but none of them worked.

Service:

@Injectable()
export class AppConfigurationService {
  private readonly _connectionString!: string;

  get connectionString() {
    return this._connectionString;
  }

  constructor(private readonly _configService: ConfigService) {
    this._connectionString = this._getConnectionStringFromEnvFile();
  }

  private _getConnectionStringFromEnvFile(): string {
    const connectionString = this._configService.get<string>('MONGODB_DB_URI');

    if (!connectionString) {
      throw new Error(
        'No connection string has been provided in the .env file.',
      );
    }

    return connectionString;
  }
}

Service Spec:

describe('#Fail connect', () => {
  let service2: AppConfigurationService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [ConfigModule.forRoot({ load: [configuration] })],
      providers: [
        AppConfigurationService,
        {
          provide: ConfigService,
          useValue: {
            get: jest.fn((key: string) => {
              if (key === 'MONGODB_DB_URI') return '';
            }),
          },
        },
      ],
    }).compile();

    service2 = module.get<AppConfigurationService>(AppConfigurationService);
  });

  it('should return erro in connection', async () => {
    expect(service2.connectionString).rejects.toThrow(
      new Error('No connection string has been provided in the .env file.'),
    );
  });
});

Error: Image Erro

Here is the error message that appears:

● #Fail connect › should return erro in connection

No connection string has been provided in the .env file.

  18 |
  19 |     if (!connectionString) {
> 20 |       throw new Error(
     |             ^
  21 |         'No connection string has been provided in the .env file.',
  22 |       );
  23 |     }

more detail than that is impossible


Solution

  • The test can't ever fire because the Test.createTestingModule doesn't ever succeed. You throw an error during the construction of the service. You could do expect(() => new AppConfigurationService({ get: () => undefined })).toThrow(new Error('No connection string has been provided in the .env file.')) so that you try to create the AppConfigurationService and catch the error that is inevitably thrown by it.