Node.js тестирует RESTful API (vows.js?) - PullRequest
8 голосов
/ 20 августа 2011

Я мог бы действительно сделать несколько советов по тестированию API RESTful, которое я создал в node.js. Существует множество рамок, и я в растерянности. Мои знания по тестированию недостаточно хороши, поэтому я пытаюсь написать эти тесты. Я попробовал vows.js, который кажется хорошим, но я не мог понять, как включить тестирование моего API, мне нужен какой-то клиент. Пример простой публикации для проверки системы входа в систему - все, что мне нужно для начала.

Ответы [ 3 ]

7 голосов
/ 20 августа 2011

Обновление через 6 месяцев

клянется - это отстой. используйте мокко

Оригинал

Обновлено с vow-is код

Вот пример vows-is из папки vows-is examples .

// simple HTTP
// Run with node example/simple-http.js

var express = require("express");
    is = require("../src/vows-is.js");

is.config({
    "server": {
        "factory": function _factory(cb) {
            var app = express.createServer();

            app.get("/", function(req, res) {
                res.send("hello world");
            })

            app.listen(3000);

            cb(app);
        },
        "uri": "http://localhost:3000",
        "kill": function _kill(app) {
            app.close();
        }
    }
});

is.suite("http request test").batch()

    .context("a request to GET /")
        .topic.is.a.request("GET /")
        .vow.it.should.have.status(200)
        .vow.it.should.have
            .header("content-type", "text/html; charset=utf-8")
        .context("contains a body that")
            .topic.is.property('body')
            .vow.it.should.be.ok
            .vow.it.should.include.string("hello world")

.suite().run({
    reporter: is.reporter
}, function() {
    console.log("finished");
    is.end();
})

Используется vows-is .

4 голосов
/ 31 августа 2011

http://blog.nodejitsu.com/rest-easy-test-any-api-in-nodejs предназначен именно для этой цели. Это DSL, стоящий поверх Vows, который упрощает процесс написания тестов с использованием Vows.

Базовый тест:

//
// Here we will configure our tests to use 
// http://localhost:8080 as the remote address
// and to always send 'Content-Type': 'application/json'
//
suite.use('localhost', 8000)
     .setHeader('Content-Type', 'application/json');
     //
     // A GET Request to /ping
     //   should respond with 200
     //   should respond with { pong: true }
     //
     .get('/ping')
       .expect(200, { pong: true })
     //
     // A POST Request to /ping
     //   should respond with 200
     //   should respond with { dynamic_data: true }
     //
     .post('/ping', { dynamic_data: true })
       .expect(200, { dynamic_data: true })
1 голос
/ 25 октября 2011

Я использовал vowsjs и request библиотеки.

Я считаю, что они самые простые, поскольку обе библиотеки правильно задокументированы и, похоже, активно развиваются и поддерживаются. (Я не нашел достаточно документов для APIeasy .)

Вот пример теста Я пишу сейчас, чтобы проверить HTTP API Couchapp:

var request = require ('request')
    , vows = require ('vows')
    , assert = require ('assert');

var BASE_URL = "http://local.todos.com:5984/todos/"
    , HEADERS = {
      'Content-Type': 'application/json'
    }
    , revisionReference;

vows.describe ('CouchApp Todos REST API')
  // --------------------------------------------
  // Testing PUTs
  // ============================================
  .addBatch ({
    "A PUT to /todos/test-host without data": {
      topic : function () {
        request ({
          uri: BASE_URL + "test-host",
          method: 'PUT',
          headers: HEADERS
        }, this.callback );
      } 
      , "should respond with 201" : function ( err, res, body ) {
        assert.equal ( res.statusCode, 201 );
      }
      , "should have an id 'test-host'" : function ( err, res, body ) {
        assert.equal ( JSON.parse( res.body )._id, 'test-host' );
      }
      , "response should contain empty todos []" : function ( err, res, body ) {
        assert.include ( JSON.parse( res.body ), 'todos' );
        assert.deepEqual ( JSON.parse( res.body ).todos, [] );
      }
    }
  })
  .addBatch ({
    "A PUT to /todos/test-host with one todo item (an object)" : {
        topic : function () {
          request ({
            uri: BASE_URL + "test-host"
            , body: JSON.stringify({
                "title" : "Testing Todo",
                "isDone" : false
              })
            , method : "PUT"
            , headers : HEADERS
          }, this.callback );
        }
        , "should respond with 201" : function ( err, res, body ) {
          assert.equal ( res.statusCode, 201 );
        }
        , "should have an id 'test-host'" : function ( err, res, body ) {
          assert.equal ( JSON.parse( res.body )._id, 'test-host' )
        }
        , "response should contain todos array with one item" : function ( err, res, body ) {
          assert.include ( JSON.parse( res.body ), 'todos' );
          assert.deepEqual ( 
            JSON.parse( res.body ).todos
            , [{
              "title" : "Testing Todo",
              "isDone" : false,
              "_id" : 0
            }] 
          );
        }
    }
  })
...