简体   繁体   English

对带有 promise 链的 nodejs class 进行单元测试

[英]Unit Test on nodejs class with chain of promise

Can you please help me to write unit test for Publish method.你能帮我为 Publish 方法编写单元测试吗? It should cover the line mentioned left side.它应该覆盖左侧提到的线。

The import statement 'amqplib' need to be mocked in jest.导入语句“amqplib”需要被嘲笑。

ch.publish and conn.close, etc should be asserted 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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM