Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Sinon callsFake在其他文件中返回相同的输出_Javascript_Node.js_Sinon_Sinon Chai - Fatal编程技术网

Javascript Sinon callsFake在其他文件中返回相同的输出

Javascript Sinon callsFake在其他文件中返回相同的输出,javascript,node.js,sinon,sinon-chai,Javascript,Node.js,Sinon,Sinon Chai,我有我的模块文件和下面的代码 无论何时承诺被拒绝,都会使用代码1调用process.exit module.exports = myPromiseReturningFunc(args) .then(el => { return true; }) .catch(err => { console.error('Error ', err) return process.exit(1); }) // here is my index.test.js const sinon =

我有我的模块文件和下面的代码

无论何时承诺被拒绝,都会使用代码1调用process.exit

module.exports = myPromiseReturningFunc(args)
.then(el => {
  return true;
})
.catch(err => {
  console.error('Error ', err)
  return process.exit(1);
})

// here is my index.test.js
const sinon = require('sinon');
describe('Index', () => {
  let exitStub;
  beforeEach(done => {  
    exitStub = sinon.stub(process, 'exit').callsFake(() => {
      return 'error'
    })
  })
  afterEach(done => {
    process.exit.restore();
  })

  it('should exit with error', (done) => {
    myModuleFunction(args).then(result => {
      expect(result).to.be.eql('error'); // passed here
      done();
    })
  })
})

// another test file
describe('Help Module', () => {
  it('should return true', (done) => {
    myModuleFunction({}).then(result => {
      console.log(result); // prints error here again :-(
      expect(result).to.be.true;
    })
  })
})

我想将process.exit存根一次,然后在其他文件中返回相同的错误,尽管其他函数正在返回问题所缺少的成功响应。没有myPromiseReturningFunc和myModuleFunction,但可能会导致问题。您的真实代码似乎与您发布的代码不同
expect(result).to.be.eql('error')
-不太可能,您没有返回
process.exit
(另外,用
error
模拟其返回值,断言调用它就足够了,这是没有意义的)<代码>预期(结果).to.be.true-为什么会出现错误?你到处滥用
done
。你要么调用它,要么不使用它。如果一个块是同步的,如果我不模拟进程,它不需要
done
@estus。exit当进程退出时,我的所有进一步测试用例都将停止,并且每当函数返回正确的值时,它都将为true,因此这是断言它的方法。也许问题是,为什么模拟响应会显示在另一个文件中?问题是,您需要将其存根,不需要使用某个值来模拟它—并且您不能在上面的代码中断言此值。我不能说为什么它会显示在另一个文件中,因为您发布的代码中存在不一致之处。您错误地使用
done
肯定会影响这一点,但我认为这会导致测试超时,而不是您描述的行为。请解决我上面提到的所有问题。另外,最好使用restore()而不是手动执行restore(),特别是因为这样可以避免人为错误。好的,我会试试mocha sinon