如何模拟a请求'在开玩笑中进行测试的节点模块
我是在开玩笑中编写测试用例的新手,我想测试“标记”功能并想模拟“请求”节点模块。假设该文件的名称是app.js,并且测试文件将是app.test.js
有人可以告诉如何编写其测试用例?
const request = require("request")
var test = {
mark: function(data,cb){
data.url = "localhost"
request(data, function(err,response,body){
if(!response){
err.response = false
}
cb(err,body)
})
}
}
module.exports = test;
I am new to writing test cases in jest and i wanted to test 'mark' function and want to mock 'request' node module. let's say this file's name is app.js and test file will be app.test.js
Can someone tell how to write its test case?
const request = require("request")
var test = {
mark: function(data,cb){
data.url = "localhost"
request(data, function(err,response,body){
if(!response){
err.response = false
}
cb(err,body)
})
}
}
module.exports = test;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确理解您的问题,您会问两个问题:
有关模拟的测试案例,我建议使用 nock 这是用于模拟网络请求的NPM模块。
在第二个问题上,我相信您应该在功能中绘制逻辑并从那里创建测试用例。考虑一下功能,查看所有其他/计算/循环,这是可能的结果,并从那里创建测试用例。
标记
函数没有很多逻辑,它是发送请求,根据响应来更新err
变量并调用回调。我们可以测试的唯一结果是,如果请求有效,则可以正确调用CB,而无需修改。如果请求返回空,请更改err var并调用回调。
为此,我们需要模拟请求并返回响应以匹配测试案例并验证CB是否正确调用(可以使用模拟完成)。
测试案例示例:
您可以阅读有关嘲笑和验证参数的更多信息,在这里。
If I understand your question correctly, you are asking two questions:
Regarding the mock, I recommend using nock which is an npm module for mocking network requests.
To the second question, I believe that you should map the logic in the function and create the test cases from there. Think about the function, look at every if else/calculation/loop and it’s possible outcomes and create test cases from there.
The
mark
function doesn’t have a lot of logic, it’s send a request, updates theerr
variable according to the response and calling the callback.The only outcome we can test to to see that if the request works, the cb is called correctly without modifications. And if the request returns empty, change the err var and call the callback.
To do so we need to mock the request and return a response to match the test case and validate that the cb was called correctly (can be done with a mock).
Test case example:
You can read more about mocking and verifying parameters here.