【问题标题】:Unit Test on nodejs class with chain of promise带有承诺链的nodejs类的单元测试
【发布时间】:2020-03-12 03:29:58
【问题描述】:

能否请您帮我为 Publish 方法编写单元测试。它应该覆盖左侧提到的线。

import 语句 'amqplib' 需要被嘲笑。

ch.publish 和 conn.close 等应该被断言

import { Injectable, Inject } from '@nestjs/common';
import * as amqp from 'amqplib';
import { RabbitMQOptions } from '../interface';
import { RABBITMQ_OPTIONS } from '../constant';

@Injectable()
export class EmitDirectService {
  constructor(
    @Inject(RABBITMQ_OPTIONS)
    private readonly rabbitMQOptions: RabbitMQOptions[],
  ) {}

  publish(queueName: string, message: string) {
    let rabbitMQOption = this.rabbitMQOptions.filter(x => x.name == queueName);
    if (!rabbitMQOption) {
      throw Error('Connection string does not exist');
    }
    amqp
      .connect(rabbitMQOption[0].connection)
      .then(function(conn) {
        return conn
          .createChannel()
          .then(function(ch) {
            var ex = rabbitMQOption[0].exchangeName;
            var ok = ch.assertExchange(ex, rabbitMQOption[0].exchangeType, {                        // Need Test Coverage
              durable: false,
            });

            return ok.then(function() {                                                             //Need test coverage all subsequent 2 line
              ch.publish(ex, rabbitMQOption[0].key, Buffer.from(message));

              return ch.close();
            });
          })
          .finally(function() {
            conn.close();                                                                           // Need test Coverage
          });
      })
      .catch(console.warn);
  }
}

【问题讨论】:

  • 这听起来很可疑,好像您的一位同事要求您测试您的代码,而现在您要求我们为您做这件事。到目前为止,您尝试过什么?
  • 按照我们的客户标准,所有代码都必须经过单元测试。所以寻求帮助。

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


【解决方案1】:

【讨论】:

  • 感谢您的回复,但它看起来正在测试 amqplib。我想在使用 amqplib 的 EmitDirectService 类中测试 publish() 方法。
  • 我使用 jest 进行单元测试,应该能够使用 this mock。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-24
  • 2016-07-25
  • 1970-01-01
  • 2018-01-31
  • 2016-05-01
相关资源
最近更新 更多