如何访问类的私有静态属性以在测试中使用它?

问题描述 投票:0回答:1

首先,我是 TypeScript 和单元测试的新手,所以这个问题对你来说可能很简单。

我正在尝试使用 sinon 对下面的代码进行单元测试。我想测试 MyService.channel 是否确认了 ConsumerFunc1 函数提供的消息。但在我的测试中,我找不到任何到达通道属性的方法。我错过了什么?

我也无法更改代码。

import amqp from 'amqplib'
import logger from '../logger'
import { msgModel } from '../msg.models'
import infoService from '../infoService'

class MyService {
    private static instance: MyService
    private static channel: amqp.Channel

    static getInstance() {
        if (!MyService.instance) {
            MyService.instance = new MyService()
        }
        return MyService.instance
    }

    async init() {
        try {
            const connection = await amqp.connect('amqp://localhost:6789')
            MyService.channel = await connection.createChannel()

            await MyService.channel.assertQueue('queue1')

            MyService.channel.consume('queue1', (msg) => this.consumeFunc1(msg))

            logger.info('MyService started!')
        } catch (error) {
            logger.error(error)
        }
    }

    async consumeFunc1(msg: amqp.ConsumeMessage) {
        if (msg) {
            const msg: msgModel = JSON.parse(msg.content.toString())

            infoService
                .getMeInfo(msg)
                .then((result) => {
                    if (result) {
                        MyService.channel.ack(msg)
                    }
                })
                .catch((error) => {
                    logger.error(error)
                })
        }
    }
}

export default MyService.getInstance()

如果我可以访问频道,我的测试将类似于;

it('should acknowledge exampleMsg successfully', async () => {
    const exampleMsg = 'something'

    const channelStub = sandbox.stub(MyService.channel, 'ack')
    await MyService.consumeFunc1(exampleMsg)

    expect(channelStub.calledOnce).toBe(true)
    assert.calledWith(channelStub, exampleMsg)
})

我是测试方面的新手,所以如果您对测试有任何建议,我也愿意接受。

node.js typescript unit-testing singleton sinon
1个回答
0
投票

当您运行

MyService.channel.ack(msg)
时,
MyService.channel
尚未定义。在创建通道存根之前,您需要运行
MyService.init()

© www.soinside.com 2019 - 2024. All rights reserved.