【问题标题】:How to stub the below senario using mocha chai sinon如何使用 mocha chai sinon 存根以下 senario
【发布时间】:2020-01-08 05:25:41
【问题描述】:

我想为下面的代码存根模拟响应,我该怎么做?

import { Storage } from "@google-cloud/storage";
const storage = new Storage();
import a from "./a.js"

export function abc(req, res) {
  a().then(result ->{
  const bucketName = result.bucketName;
  const fileName = "Sample.json";
  const file = storage.bucket(bucketName).file(result.fileName);
  const myfile = file.createReadStream();
  let buffer = "";
  myfile
    .on("data", function(a) {
      buffer += a;
    })
    .on("end", function() {
      console.log(buffer);
      res.status(200).send(buffer);
    });
    });
}

import a from "./a.js" 是异步函数,我需要使用 mocha chai 编写单元测试。

【问题讨论】:

  • 您是否正确导出了 a.js 中的模块?看看这个tutorial。让我知道是否适合您。否则,我可以进一步帮助您。
  • 是的,function const a= async () => { //逻辑返回结果 } module.exports = a;

标签: unit-testing google-cloud-functions sinon sinon-chai


【解决方案1】:

按照以下步骤在 Nodejs 中导出和导入:

a.js

const a= async () => { 
//logic 
   return result 
}
module.exports = { a: a };

云功能

const func = require('./a.js');
//Use the function like following: 
func.a()

【讨论】:

  • 嗨@Nibrass,我已经尝试如上所示并存根结果,但出现以下错误 TypeError: a.a(...).then is not a function --- 我存根 sinon.stub 的方式(a, "a").callsFake(() => { return { resultStub }; });
  • @Tapas Vishal,你能用整个代码更新帖子吗?您认为问题出在 sinon 库的工作方式上吗?
  • 我知道我知道 sinon,但问题是如何模拟我将从函数中获得的 a().then(result =>{}) 结果
  • 你是按照下面的方式做的吗,func.a().then(result =>{}) ?
  • 是的,嗨@slideshowp2你能帮我解决上述情况吗
猜你喜欢
  • 2020-08-20
  • 2017-10-08
  • 1970-01-01
  • 2017-10-23
  • 2021-12-10
  • 2015-12-01
  • 2018-04-08
  • 2016-08-04
  • 1970-01-01
相关资源
最近更新 更多