【发布时间】:2020-03-06 19:12:02
【问题描述】:
我已经尝试解决这个问题好几天了; 使用 mocha 为这个案例创建测试:
app.post('/approval', function(req, response){
request.post('https://git.ecommchannel.com/api/v4/users/' + req.body.content.id + '/' + req.body.content.state + '?private_token=blabla', function (error, resp, body) {
if (resp.statusCode == 201) {
//do something
} else {
response.send("failed"), response.end();
}
});
} else {
response.send("failed"), response.end();
}
});
});
我尝试了几种方法,使用 supertest 来测试 '/approval' 并使用 nock 来测试对 git api 的 post 请求。但它总是把“statusCode”变成未定义的。我认为这是因为 index.js 中对 git api 的请求不在某个函数内(?) 所以我不能实现这样的事情: https://codeburst.io/testing-mocking-http-requests-with-nock-480e3f164851 或 https://scotch.io/tutorials/nodejs-tests-mocking-http-requests
const nockingGit = () => {
nock('https://git.ecommchannel.com/api/v4/users')
.post('/1/yes', 'private_token=blabla')
.reply(201, { "statusCode": 201 });
};
it('approval', (done) => {
let req = {
content: {
id: 1,
state: 'yes'
},
_id: 1
}
request(_import.app)
.post('/approval')
.send(req)
.expect(200)
.expect('Content-Type', /html/)
.end(function (err, res) {
if (!err) {
nockingGit();
} else {
done(err);
}
});
done();
})
然后我尝试使用supertest作为promise
it('approve-block-using-promise', () => {
return promise(_import.app)
.post('/approval')
.send(req = {
content: {
id: 1,
state: 'yes'
},
_id: 1
})
.expect(200)
.then(function(res){
return promise(_import.app)
.post("https://git.ecommchannel.com/api/v4/users/")
.send('1/yes', 'private_token=blabla')
.expect(201);
})
})
但它给出了错误:ECONNEREFUSED:连接被拒绝。我没有找到解决该错误的任何解决方案。一些消息来源说它需要 done() .. 但它给出了另一个错误消息,'确保调用了“done()”>。
那么我找到了另一种方法,使用异步 (https://code-examples.net/en/q/141ce32)
it('should respond to only certain methods', function(done) {
async.series([
function(cb) { request(_import.app).post('/approval')
.send(req = {
content: {
id: 1,
state: 'yes'
},
_id: 1
})
.expect(200, cb); },
function(cb) { request(_import.app).post('/https://git.ecommchannel.com/api/v4/users/').send('1/yes', 'private_token=blabla').expect(201, cb); },
], done);
});
它给出了这个错误:预期 201“已创建”,得到 404“未找到”。好吧,如果我在浏览器中打开https://git.ecommchannel.com/api/v4/users/1/yes?private_token=blabla,它确实会返回 404。但我期望的是我已经从单元测试中注入了对 201 的响应;所以无论实际响应是什么,statusCode 都应该是 201,对吧? 但是既然它给出了那个错误,这是否意味着单元测试真的将请求发送到api? 请帮我解决这个问题;如何测试我分享的第一个代码。 我真的是单元测试的新手。
【问题讨论】:
-
您能否更新您的问题以包含测试的
nock部分。此外,在您的第一个测试示例中,您向本地应用程序发出了两个请求。对您的应用的第一个或第二个请求是错误的吗? -
嗨,马特,我已将 nock 部分包含在问题中。我使用 supertest 作为 promise 的测试在第二个请求时出错。
标签: unit-testing mocha.js supertest nock supertest-as-promised