I wrote a NodeJS application using an expression that proxies some calls to an external API. So I am trying to write unit test with Mocha and Sinon. My goal is to test the application without an internet connection, so I'm trying to mock https requests and return response comments.
I have a problem: I cannot find examples or training materials that are relevant to my case. The node application listens on port 8081 for HTTP requests and then proxies them to another site. I want to test the application without having to send a request to these external servers. I am trying to do this below and I put the json answers that I want to send back to the server.respondsWith () function.
Am I doing it right by making an ajax call with tea? or should I somehow send requests in my application. Any help is appreciated.
var assert = require('assert');
var chai = require('chai');
var spies = require('chai-spies');
var chaiHttp = require('chai-http');
var https = require('https');
var should = chai.should();
var expect = chai.expect;
var sinon = require('sinon');
chai.use(spies);
chai.use(chaiHttp);
describe('Car Repository', function() {
var server;
before(function() {
server = sinon.fakeServer.create();
});
after(function() {
server.restore();
});
var url = 'http://127.0.0.1:8081';
it('should succeed and return a list of cars', function(done) {
server.respondWith('POST', 'https://api.sandbox.cars.com/v2/token_endpoint', JSON.stringify({"access_token":"1t3E4IykfpJAbuFsdfM2oFAo5raB5vhfOV0hAYe","token_type":"bearer","expires_in":604800}));
server.respondWith('GET', url+'/cars', JSON.stringify({'test':'this works'}));
chai.request(url)
.get('/cars')
.end(function(err, res) {
if (err) {
throw err;
}
res.should.have.status(200);
res.body.should.have.property('test');
console.log(res.body);
done();
});
});
});
source
share