1

This is the code where i am writing unit test in jest:

import { Connector, DbConnector } from "@custom/connector"; // package contains mongodb operations.

export class DBService {
  private connector: Connector;
  constructor() {
    this.connector = DbConnector.getInstance();
    this.connector.connect();
  }

  public async saveData() {
    return this.connector.update(collName, condition, update, options).then(() => {
       // logger
    });
 }
}

unit test:

import { Connector, DbConnector } from "@custom/connector";
import DBService from "service.ts";

it("success", async () => {

    const db = new DBService ();
    const records = { ok: 1 };
    jest.spyOn(DbConnector, "getInstance").mockImplementation((): any => {
      return {
        connect() { return Promise.resolve(); },
        update() { return Promise.resolve(records); },
      };
    });

    expect(await db.saveData()).resolves.toEqual(records); // Not sure what to do here
  });

When i run, i am getting below error:

Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

Can somebody help me where i am missing? Any help would be really appreciated.

Thanks in advance.

1 Answer 1

2

Here is the unit test solution:

dbService.ts:

import { Connector, DbConnector } from './dbConnector';

export class DBService {
  private connector: Connector;
  constructor() {
    this.connector = DbConnector.getInstance();
    this.connector.connect();
  }

  public async saveData() {
    const collName = 'collName';
    const condition = 'condition';
    const update = {};
    const options = {};
    return this.connector.update(collName, condition, update, options).then((reconds) => {
      return reconds;
    });
  }
}

dbConnector.ts:

export interface Connector {
  connect(): void;
  update(collName, condition, update, options): Promise<any>;
}

export class DbConnector implements Connector {
  public static connector: Connector;
  public static getInstance() {
    if (this.connector) {
      return this.connector;
    }
    this.connector = new DbConnector();
    return this.connector;
  }
  private constructor() {}
  public connect() {
    console.log('connect to db');
  }
  public async update(collName, condition, update, options) {
    return 'real update';
  }
}

dbService.test.ts:

import { DBService } from './dbService';
import { DbConnector } from './dbConnector';

describe('61815803', () => {
  it('should pass', async () => {
    const records = { ok: 1 };
    const dbConnectorMock = {
      connect: jest.fn(),
      update: jest.fn().mockResolvedValueOnce(records),
    };
    jest.spyOn(DbConnector, 'getInstance').mockReturnValueOnce(dbConnectorMock);
    const dbService = new DBService();
    const actual = await dbService.saveData();
    expect(actual).toEqual({ ok: 1 });
    expect(DbConnector.getInstance).toBeCalledTimes(1);
    expect(dbConnectorMock.connect).toBeCalledTimes(1);
    expect(dbConnectorMock.update).toBeCalledWith('collName', 'condition', {}, {});
  });
});

unit test results with coverage report:

 PASS  stackoverflow/61815803/dbService.test.ts (10.698s)
  61815803
    ✓ should pass (6ms)

----------------|---------|----------|---------|---------|-------------------
File            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------------|---------|----------|---------|---------|-------------------
All files       |      76 |        0 |   55.56 |   73.91 |                   
 dbConnector.ts |      50 |        0 |      20 |   45.45 | 9-13,17,20        
 dbService.ts   |     100 |      100 |     100 |     100 |                   
----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.495s

You may want to set the timeout config globally for jestjs like: jest.setup.js:

jest.setTimeout(10 * 1000);

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'node',
  setupFilesAfterEnv: [
    './jest.setup.js',
  ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.