gpt4 book ai didi

node.js - TDD 测试第一个 Node Js Express Rest Api - 单元测试中间件/ Controller /路由

转载 作者:太空宇宙 更新时间:2023-11-03 23:27:21 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何首先测试我的 Node js Rest api 应用程序。到目前为止我一直在使用 nock拦截和模拟任何 http 调用,并通过该调用将我的服务作为组件进行测试。 (组件测试?)我想开始对我的应用程序进行单元测试,以便我的测试金字塔更加平衡,并且测试将更容易编写。

在网上搜索我得到了这种方法: http://www.slideshare.net/morrissinger/unit-testing-express-middleware

var middleware = require('./middleware');
app.get('example/uri', function (req, res, next) {
middleware.first(req, res)
.then(function () { next(); })
.catch(res.json)
.done();
}, function (req, res, next) {
middleware.second(req, res)
.then(function () { next(); })
.catch(res.json)
.done();
});

(基本上是拉出中间件并进行测试)

由于本演示是 2014 年的,我想知道当前用于单元测试 Express 应用程序的最新方法是什么?

最佳答案

我遇到了同样的问题,我使用了另一种方法。首先,我创建了一个包含在所有测试中的文件,该文件启动 Node 并导出发送 http 请求的函数:

process.env.NODE_ENV = 'test';
var app = require('../server.js');

before(function() {
server = app.listen(3002);
});

after(function(done) {
server.close(done);
});

module.exports = {
app: app,
doHttpRequest: function(path, callback) {
var options = {
hostname: 'localhost',
port: 3002,
path: path,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Content-Length': 0
}
};

var req = http.request(options,
function(response) {
response.setEncoding('utf8');

var data = '';
response.on('data', function(chunk) {
data += chunk;
});

response.on('end', function() {
callback(data, response.statusCode);
});
});

req.end();
}
}

然后我使用之前声明的方法调用我的服务器:

var doHttpRequest = require('./global-setup.js').doHttpRequest;
var expect = require('chai').expect;

describe('status page test', function() {

it('should render json', function(done){
doHttpRequest('/status', function(response) {
expect(JSON.parse(response).status).to.eql('OK');
done();
})
});
});

关于node.js - TDD 测试第一个 Node Js Express Rest Api - 单元测试中间件/ Controller /路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42329054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com