我正在学习 nodejs 并为 shelljs 函数编写了这个包装器,实际上它似乎按预期工作。
/**
* Wrapper for Shelljs.exec to always return a promise
*
* @param {String} cmd - bash-compliant command string
* @param {String} path - working directory of the process
* @param {Object} _shell - alternative exec function for testing.
* @returns {String}
* @throws {TypeError}
*/
function shellExec(cmd, path, _shell = shelljs){
if( typeof _shell.exec !== "function") throw new TypeError('_shell.exec must be a function');
return new Promise((resolve, reject) => {
let options = { cwd: path, silent: true, asyc: true }
// eslint-disable-next-line no-unused-vars
return _shell.exec(cmd, options, (code, stdout, stderr) => {
// shelljs.exec does not always return a code
if(stderr) {
return reject(stderr);
}
return resolve(stdout);
});
});
}
但是,当我尝试对其进行单元测试时,该功能会超时。我已经阅读了 mochajs 文档中关于异步代码、promise或async/await的测试。我想使用一个sinon fake 来返回一个我知道有效的承诺。Mocha 告诉我错误是该函数没有通过错误返回承诺Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves
。我想我已经不正确地构建了假货,但我看不出我应该怎么做。
const { expect, use } = require('chai');
const sinon = require('sinon');
const sinonChai = require("sinon-chai");
const utils = require('../utility/exec');
use(sinonChai);
it('sinon fake should resolve', async () =>{
const fake = sinon.fake.resolves('resolved');
const result = await fake();
expect(result).to.equal('resolved');
});
describe('Utility Functions', () =>{
describe('shellExec', () =>{
it('should accept an alternate execute function', async () =>{
const fakeShell = { exec: sinon.fake.resolves('pass') };
const result = await utils.shellExec('pwd', 'xyz', fakeShell);
expect(result).to.equal('pass');
expect(fakeShell.exec).to.have.been.calledOnce;
});
});
});