Mocha로 Express 앱을 테스트하려면 어떻게하나요?
테스트를 위해 내 익스프레스 앱에 shouldjs와 mocha를 추가했지만 내 애플리케이션을 테스트하는 방법이 궁금합니다. 다음과 같이하고 싶습니다.
app = require '../app'
routes = require '../src/routes'
describe 'routes', ->
describe '#show_create_user_screen', ->
it 'should be a function', ->
routes.show_create_user_screen.should.be.a.function
it 'should return something cool', ->
routes.show_create_user_screen().should.be.an.object
물론 해당 테스트 스위트의 마지막 테스트는 res.render 함수 (show_create_user_screen 내에서 호출 됨)가 정의되지 않았 음을 med에게 알려줍니다. 아마도 서버가 실행되지 않고 구성이 완료되지 않았기 때문일 것입니다. 그래서 다른 사람들이 테스트를 어떻게 설정했는지 궁금합니다.
좋습니다. 먼저 라우팅 코드를 테스트하는 것이 원할 수도 있고 원하지 않을 수도 있지만 일반적으로 익스프레스 또는 사용중인 프레임 워크와 분리 된 순수 자바 스크립트 코드 (클래스 또는 함수)에서 흥미로운 비즈니스 로직을 분리하려고합니다. 바닐라 모카 테스트를 사용하여 테스트합니다. 모카에서 구성한 경로를 실제로 테스트하려면 모의 req, res
매개 변수를 미들웨어 함수에 전달 하여 익스프레스 / 연결과 미들웨어 간의 인터페이스를 모방해야합니다.
간단한 경우에 다음 res
과 같은 render
함수 로 모의 객체를 만들 수 있습니다 .
describe 'routes', ->
describe '#show_create_user_screen', ->
it 'should be a function', ->
routes.show_create_user_screen.should.be.a.function
it 'should return something cool', ->
mockReq = null
mockRes =
render: (viewName) ->
viewName.should.exist
viewName.should.match /createuser/
routes.show_create_user_screen(mockReq, mockRes).should.be.an.object
또한 FYI 미들웨어 함수는 특정 값을 반환 할 필요가 없으며 req, res, next
테스트에서 집중해야하는 매개 변수를 사용하여 수행합니다.
의견에서 요청한 JavaScript는 다음과 같습니다.
describe('routes', function() {
describe('#show_create_user_screen', function() {
it('should be a function', function() {
routes.show_create_user_screen.should.be.a["function"];
});
it('should return something cool', function() {
var mockReq = null;
var mockRes = {
render: function(viewName) {
viewName.should.exist;
viewName.should.match(/createuser/);
}
};
routes.show_create_user_screen(mockReq, mockRes);
});
});
});
connect.js 테스트 스위트 에서 대안을 찾았습니다.
그들은 서버를 포트에 바인딩하지 않고 모형을 사용하지 않고 연결 앱을 테스트하기 위해 supertest 를 사용 하고 있습니다.
다음은 connect의 정적 미들웨어 테스트 스위트에서 발췌 한 것입니다 (모카를 테스트 러너로 사용하고 어설 션에 대해 수퍼 테스트를 사용함).
var connect = require('connect');
var app = connect();
app.use(connect.static(staticDirPath));
describe('connect.static()', function(){
it('should serve static files', function(done){
app.request()
.get('/todo.txt')
.expect('contents', done);
})
});
이것은 익스프레스 앱에서도 작동합니다.
SuperTest를 시도하면 서버 시작 및 종료가 처리됩니다.
var request = require('supertest')
, app = require('./anExpressServer').app
, assert = require("assert");
describe('POST /', function(){
it('should fail bad img_uri', function(done){
request(app)
.post('/')
.send({
'img_uri' : 'foobar'
})
.expect(500)
.end(function(err, res){
done();
})
})
});
mocha는 bdd 테스트를 위해 before, beforeEach, after 및 afterEach와 함께 제공됩니다. 이 경우 설명 호출에서 before를 사용해야합니다.
describe 'routes' ->
before (done) ->
app.listen(3000)
app.on('connection', done)
도우미 http 클라이언트뿐만 아니라 도우미로 사용할 TestServer 클래스를 설정하고 실제 http 서버에 실제 요청을하는 것이 가장 쉽다는 것을 알았습니다. 대신이 물건을 조롱하고 스텁하고 싶은 경우가있을 수 있습니다.
// Test file
var http = require('the/below/code');
describe('my_controller', function() {
var server;
before(function() {
var router = require('path/to/some/router');
server = http.server.create(router);
server.start();
});
after(function() {
server.stop();
});
describe("GET /foo", function() {
it('returns something', function(done) {
http.client.get('/foo', function(err, res) {
// assertions
done();
});
});
});
});
// Test helper file
var express = require('express');
var http = require('http');
// These could be args passed into TestServer, or settings from somewhere.
var TEST_HOST = 'localhost';
var TEST_PORT = 9876;
function TestServer(args) {
var self = this;
var express = require('express');
self.router = args.router;
self.server = express.createServer();
self.server.use(express.bodyParser());
self.server.use(self.router);
}
TestServer.prototype.start = function() {
var self = this;
if (self.server) {
self.server.listen(TEST_PORT, TEST_HOST);
} else {
throw new Error('Server not found');
}
};
TestServer.prototype.stop = function() {
var self = this;
self.server.close();
};
// you would likely want this in another file, and include similar
// functions for post, put, delete, etc.
function http_get(host, port, url, cb) {
var options = {
host: host,
port: port,
path: url,
method: 'GET'
};
var ret = false;
var req = http.request(options, function(res) {
var buffer = '';
res.on('data', function(data) {
buffer += data;
});
res.on('end',function(){
cb(null,buffer);
});
});
req.end();
req.on('error', function(e) {
if (!ret) {
cb(e, null);
}
});
}
var client = {
get: function(url, cb) {
http_get(TEST_HOST, TEST_PORT, url, cb);
}
};
var http = {
server: {
create: function(router) {
return new TestServer({router: router});
}
},
client: client
};
module.exports = http;
참고 URL : https://stackoverflow.com/questions/8831984/how-do-i-test-my-express-app-with-mocha
'Program Tip' 카테고리의 다른 글
함수 인수를 사용한 메서드 체인 (0) | 2020.11.17 |
---|---|
ALTER 테이블-MySQL에 AUTOINCREMENT 추가 (0) | 2020.11.17 |
Json에서 getString ()과 optString ()의 차이점 (0) | 2020.11.17 |
Pandas 데이터 프레임의 열을 1 위로 이동 하시겠습니까? (0) | 2020.11.17 |
8 개의 논리적 참 / 거짓 값을 1 바이트 안에 저장합니까? (0) | 2020.11.17 |