سؤال

I'm working on testing my node.js code with Zombie.js. I have the following api, which is in POST method:

/api/names

and following code in my test/person.js file:

it('Test Retreiving Names Via Browser', function(done){
    this.timeout(10000);
    var url = host + "/api/names";
    var browser = new zombie.Browser();
    browser.visit(url, function(err, _browser, status){
       if(browser.error)
       {
           console.log("Invalid url!!! " + url);
       }
       else
       {
           console.log("Valid url!!!" + ". Status " + status);
       }
       done();
    });
});

Now, when I execute the command mocha from my terminal, it gets into browser.error condition. However, if I set my API to get method, it works as expected and gets into Valid Url (else part). I guess this is because of having my API in post method.

PS: I don't have any Form created to execute the queries on button click as I'm developing a back-end for mobile.

Any help on how to execute APIs with POST method would be appreciated.

هل كانت مفيدة؟

المحلول

Zombie is more for interacting with actual webpages, and in the case of post requests actual forms.

For your test use the request module and manually craft the post request yourself

var request = require('request')
var should = require('should')
describe('URL names', function () {
  it('Should give error on invalid url', function(done) {
    // assume the following url is invalid
    var url = 'http://localhost:5000/api/names'
    var opts = {
      url: url,
      method: 'post'
    }
    request(opts, function (err, res, body) {
      // you will need to customize the assertions below based on your server

      // if server returns an actual error
      should.exist(err)
      // maybe you want to check the status code
      res.statusCode.should.eql(404, 'wrong status code returned from server')
      done()
    })
  })

  it('Should not give error on valid url', function(done) {
    // assume the following url is valid
    var url = 'http://localhost:5000/api/foo'
    var opts = {
      url: url,
      method: 'post'
    }
    request(opts, function (err, res, body) {
      // you will need to customize the assertions below based on your server

      // if server returns an actual error
      should.not.exist(err)
      // maybe you want to check the status code
      res.statusCode.should.eql(200, 'wrong status code returned from server')
      done()
    })
  })
})

For the example code above you will need the request and should modules

npm install --save-dev request should
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top