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

编程入门 行业动态 更新时间:2024-10-11 01:20:55

开玩笑地进行异步测试时出现超时<a href=https://www.elefans.com/category/jswz/34/1771449.html style=错误"/>

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

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

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:

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

提前感谢。

回答如下:

这里是单元测试解决方案:

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',
  ]
}

更多推荐

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

本文发布于:2024-05-07 15:35:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756946.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!