Node.js + Chai / Mocha / Should: perform several tests against the same answer

I am using something very similar to the following to run a series of API tests using Mocha. This is great, but each test requires a separate API call. I want to use the same API call and run multiple tests against this answer. I read that you can use before for this, but not one of the examples on the Internet actually shows its work with API calls?

 var chai = require('chai'); var request = require('request'); var async = require('async'); var assert = chai.assert, expect = chai.expect, should = chai.should(); describe('/', function () { it('should return 200', function (done) { request.get('http://localhost:8000', function (err, res, body) { res.should.have.status(200); done(); }); }); it('should say "Hello, world!"', function (done) { request.get('http://localhost:8000', function (err, res, body) { body.should.have.property('type', 'aType'); done(); }); }); }); 
+5
source share
1 answer

You can do this with the before function, for example ...

 var chai = require('chai'); var request = require('request'); var async = require('async'); var assert = chai.assert, expect = chai.expect, should = chai.should(); describe('/', function () { var firstRequest; before(function(done) { request.get('http://localhost:8000', function(err, res, body) { firstRequest = { err:err, res:res, body:body }; done(); }); }); it('should return 200', function (done) { firstRequest.res.should.have.status(200); done(); }); it('should say "Hello, world!"', function (done) { firstRequest.body.should.have.property('type','aType'); done(); }); }); 

However, if you don’t have a really good reason for this, I think you better combine the tests.

 var chai = require('chai'); var request = require('request'); var async = require('async'); var assert = chai.assert, expect = chai.expect, should = chai.should(); describe('/', function () { it('should return 200 and say "Hello, world!"', function (done) { request.get('http://localhost:8000', function (err, res, body) { res.should.have.status(200); body.should.have.property('type', 'aType'); done(); }); }); }); 

If the test fails, Mocha will report a specific reason why it failed, although there are two claims.

+5
source

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


All Articles