在 NodeJs 中使用 mocha 进行模拟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12146889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:13:56  来源:igfitidea点击:

Mocking using mocha in NodeJs

node.jsmockingmocha

提问by ravi tandon

How can I mock a client and a server in Mocha using NodeJs. Specifically, I have the following code:

如何使用 NodeJs 在 Mocha 中模拟客户端和服务器。具体来说,我有以下代码:

app.post ('path name', function (req, res) { 
  // Some Action 
  res.send(response); 
});

I want to mock the req, resparameters and test res(status, header, message).

我想模拟req,res参数和测试res(状态、标题、消息)。

回答by Peter Lyons

Mocha itself doesn't provide mock/stub/spy type functionality. Sinonis a popular library that does. The home page includes examples of testing ajax as well as their Fake XMLHTTPRequest object.

Mocha 本身不提供模拟/存根/间谍类型的功能。Sinon是一个受欢迎的图书馆。主页包括测试 ajax 的示例以及它们的 Fake XMLHTTPRequest 对象。

回答by ravi tandon

I found Node-Fakewebuseful

我发现Node-Fakeweb很有用

var request = require('request'); 
  // Mocking a client request 
  request.get({ uri: 'URI', body: 'body' }, function (err, resp, body) {
    // Some Action
  });
}); 

回答by sam100rav

You can use mocha with supertestto mock a request. Here is a wonderful tutorial about how to do it: http://thewayofcode.wordpress.com/2013/04/21/how-to-build-and-test-rest-api-with-nodejs-express-mocha/

您可以使用 mocha 和supertest来模拟请求。这是一个关于如何做到这一点的精彩教程:http: //thewayofcode.wordpress.com/2013/04/21/how-to-build-and-test-rest-api-with-nodejs-express-mocha/