0

我正在尝试使用 Jest 为使用 ssh2-sftp-client 模块的函数“DownloadFile”创建一个测试套件。

我想检查在 DownlaodFile 函数中是否调用了以下方法:

  1. 连接
  2. 快速获取
  3. 结尾

下载服务.js

const Client = require('ssh2-sftp-client');
const sftp = new Client();

const logDownloadChunks = (total_transferred, chunk, total) => {
    console.log(`${total_transferred}/${total} chunks transferred`)
}

const downloadFile = async ({
                                localPath,
                                remotePath,
                                sftp: {
                                    host,
                                    username,
                                    password,
                                    concurrency,
                                    chunkSize
                                }
                            }) => {

    try {
        console.log('\nConnecting to server...')
        await sftp.connect({
            host,
            username,
            password
        })
        console.log('Downloading packages...')
        await sftp.fastGet(remotePath, localPath, {
            // number of concurrent reads to use
            concurrency,
            // size of each read in bytes
            chunkSize,
            // callback called each time a chunk is transferred
            step: logDownloadChunks
        })
        console.log('Download complete')
    } catch (error) {
        throw error
    } finally {
        await sftp.end()
    }
}

我知道问题是我正在尝试测试在测试中创建的类的实例,而不是 downloadFile 函数中的实例。

我收到以下错误:

    expect(jest.fn()).toBeCalledTimes(expected)

    Expected number of calls: 1
    Received number of calls: 0

      36 |     sftp = new Client()
      37 |     await downloadFile(sftpConfig)
    > 38 |     expect(sftp.connect).toBeCalledTimes(1)
         |                          ^
      39 | })

我不明白的是如何测试是否为 ssh2-sftp-client 类的任何实例调用了这些方法。

下载Service.test.js

const Client = require('ssh2-sftp-client')
const {downloadFile} = require('../src/downloadService');
jest.mock('ssh2-sftp-client')

let sftp, sftpConfig
beforeEach(() => {
    sftpConfig = {
        localPath: 'some/local/path',
        remotePath: 'some/remote/path',
        sftp: {
            host: 'mock-host.sftp.com',
            username: 'usr',
            password: 'psw',
            concurrency: 64,
            chunkSize: 32768
        }
    }
})

afterEach(() => {
    jest.clearAllMocks()
})

test('sftp.connect called once', async () => {
    sftp = new Client()
    await downloadFile(sftpConfig)
    expect(sftp.connect).toHaveBeenCalledTimes(1)
    expect(sftp.fastGet).toBeCalledTimes(1)
    expect(sftp.end).toBeCalledTimes(1)
})
4

0 回答 0