2016-04-26 137 views
-1

刚刚创建了一个新的快速开源中间件项目。我希望能够从它生成的路由单元测试json响应...无论如何,我可以做到这一点,而不会实际发射一个咕噜发球和检查网址?节点快速单元测试JSON响应

那么目标将是好歹运行路线,但不是JSON发送到浏览器,我可以将其存储在一个变量的/ etc ...

什么中间件的作用是基于在JavaScript注释路线文件。

https://github.com/kmgilbert100/annotation-route-loader

我想提出我的单元测试包括根据试验/路由/ **/*

注意app.use(loader)的JSON响应,你可以在上面看到的URL将加载所有路由

下面是当前摩卡测试

// npm modules 
const chai = require('chai'); 
const _ = require('lodash'); 
const express = require('express'); 
// local modules 
var routeLoader = require('../src/index'); 
// testing module methods 
const assert = chai.assert; 

describe('annotation-route-loader',() => { 

    // store collection of routes 
    var routePaths = []; 

    before("Create collection to check from",() => { 

     var loader = routeLoader({ 
      baseUrl: '/', 
      path: './routes', 
      pattern: '**/*.js', 
      params: { 
       sports: [ 
        'footbal', 
        'baseball', 
        'motocross', 
        'hockey' 
       ] 
      } 
     }); 

     loader['stack'].forEach(stack => { 

      routePaths.push({ 
       path: stack.route.path, 
       methods: stack.route.methods 
      }) 

     }) 

    }); 


    it('Should make sure the default path is valid', (done) => { 

     // Try And Find Path 
     var defaultPath = _.find(routePaths, {path: '/'}); 
     assert.isObject(defaultPath); 
     assert.isTrue(defaultPath.methods.get); 

     // Make Callback 
     done() 

    }); 


    it('Should make sure the sports path is valid', (done) => { 

     // Try And Find Path 
     var defaultPath = _.find(routePaths, {path: '/sports'}); 
     assert.isObject(defaultPath); 
     assert.isTrue(defaultPath.methods.get); 

     // Make Callback 
     done() 

    }); 


    it('Should make sure the sports list path is valid', (done) => { 

     // Try And Find Path 
     var defaultPath = _.find(routePaths, {path: '/sports/list'}); 
     assert.isObject(defaultPath); 
     assert.isTrue(defaultPath.methods.get); 

     // Make Callback 
     done() 

    }); 

}) 
+1

分享一些代码,请。你有什么尝试?你有没有尝试过使用mock? –

+0

提供 - 我注销了路由器实例/ etc无法找到任何帮助..没有挖出太多表达api tho,看看它如何处理它 –

+0

看看邮差,它有测试套件内置,允许您使用预定义的json测试endpoint/api,并且测试用例可以用JS编写。 –

回答

0

感谢您的意见!

https://github.com/visionmedia/supertest

结束了使用supertest来完成这项工作!

请参见下面的一段:

var request = require('supertest'); 
var express = require('express'); 

var app = express(); 

app.get('/user', function(req, res) { 
    res.status(200).json({ name: 'tobi' }); 
}); 

request(app) 
    .get('/user') 
    .expect('Content-Type', /json/) 
    .expect('Content-Length', '15') 
    .expect(200) 
    .end(function(err, res) { 
    if (err) throw err; 
    });