在开玩笑地进行异步测试时出现超时错误

时间:2020-05-15 09:15:42

标签: javascript node.js unit-testing asynchronous jestjs

这是我开玩笑编写单元测试的代码:

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
    });
 }
}

单元测试:

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
  });

我跑步时出现以下错误:

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:

有人在我想念的地方可以帮助我吗?任何帮助将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:2)

这是单元测试解决方案:

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', {}, {});
  });
});

具有覆盖率报告的单元测试结果:

 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

您可能想为jestjs全局设置timeout配置,例如: 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',
  ]
}