0

我需要测试一个使用 shh2-sftp-client 库在 sftp 机器上将文件从本地路径写入远程路径的函数。

我自己的功能如下:

 //fileshareAPI.js
 saveFile: function saveFile(folder, filename, file) {
    uploadValidateBody(folder, filename, file);
    const Client = require('ssh2-sftp-client');
    const sftp = new Client();
    return sftp.connect(sftpConfig)
    .then(() => {
        console.log('connection OK')
        fs.writeFile(filename, file, { encoding: 'base64' }, (err) => console.log(err));
        console.log(`${basePath}${folder}`)
        return sftp.mkdir(`/${basePath}${folder}`, true);
    }).then(() => {
        return sftp.put(filename, `/${basePath}${folder}/${filename}`);
    }).then(() => {
        fs.unlinkSync(filename);
        return true;
    }).catch((err) => {
        console.log('an erro occurred')
        throw new InternalServerError(5002, err.message)
    }).finally(() => {return sftp.end()})
}

我创建了自己的测试类

const sftp = require('ssh2-sftp-client') //import of the class from the library
jest.mock('ssh2-sftp-client') //default mock. All methods are undefined
describe('test', () => {
beforeAll(() => {
    sftp.mockImplementation(() => {
        return {
            connect: jest.fn().mockReturnValue(Promise.reject(new Error('error'))),
            mkdir: jest.fn().mockReturnValue(Promise.resolve(true)),
            put: jest.fn().mockReturnValue(Promise.resolve(true)),
            end: jest.fn().mockReturnValue(Promise.resolve(true))
        }
    })
});
it('should throw exception', () => {
    return expect(fileshareUtilities.saveFile('a', 'b', 'c')).rejects.toThrow('error')
});
});

尽管通过 mockImplementation 方法声明了新的构造函数,但我总是得到默认模拟返回的构造函数。事实上,我收到以下错误:

TypeError: Cannot read property 'then' of undefined

  65 |     saveFile: function saveFile(folder, filename, file) {
  66 |         uploadValidateBody(folder, filename, file);
> 67 |         return sftp.connect(sftpConfig)
     |                ^
  68 |         .then(() => {
  69 |             console.log('connection OK')
  70 |             fs.writeFile(filename, file, { encoding: 'base64' }, (err) => console.log(err));

  at Object.saveFile (lib/apis/fileshare/fileshareAPI.js:67:16)
  at Object.<anonymous> (test/fileshare.test.js:30:42)

如何为每个测试覆盖不同的构造方法,以便可以测试 saveFile 中调用的函数链中的各个点?

4

1 回答 1

1

我希望它对其他人有用,但我已经找到了解决方案。我总是默认定义模拟,但随后我在ssh2-sftp-client库类的实例上调用mockImplementation()方法,模拟单个函数。对于每个测试,我都会覆盖每个函数的返回值。

这里有一个例子:

const sftp = require('ssh2-sftp-client');
const mockConnect = jest.fn();
const mockMkdir = jest.fn();
const mockPut = jest.fn();
const mockEnd = jest.fn();
const mockRename = jest.fn();
sftp.mockImplementation(() => {
  return {
    connect: mockConnect,
    mkdir: mockMkdir,
    put: mockPut,
    rename: mockRename,
    end: mockEnd
 }
});


it('test mkdir', async() => {
mockConnect.mockReturnValue(Promise.resolve(true));
mockMkdir.mockReturnValue(Promise.reject(new Error('permission danied mkdir')))
await expect(fileshareUtilities.saveFile(inputFolder, inputFilename,   'file')).rejects.toThrow(new InternalServerError(5002, "permission danied mkdir"));

});

于 2020-11-14T21:39:35.383 回答