API call with POST method through Zombie.js browser

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

/api/names 

and the following code in 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 mocha command from my terminal, it goes into browser.error state. However, if I install my API to get the method, it works as expected and will fall into the Valid URL (another part). I assume this is because my API is in the post method.

PS: I don’t have any Form created to execute requests at the click of a button, since I am developing a back-end for mobile devices.

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

+4
source share
1 answer

Zombie is more suitable for interacting with actual web pages, and in the case of actual post request forms.

For your testing, use the request module and manually create a submit request

 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 code above, you need request and should modules

 npm install --save-dev request should 
+1
source

Source: https://habr.com/ru/post/1482508/


All Articles