我需要测试一个使用 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 中调用的函数链中的各个点?