Please be gentle with me. I'm new to async coding and have been thrown headfirst into an intensive project using node to develop and API server. I'm loving it but some things aren't coming naturally.
Our project is built using express js. We have a file, server.js where we instantiate an express server which in turn instantiates our router and so on. I need to integration test this now (partially) complete server. Normally what I do is from the command line run '%node server.js' and then using either python requests or curl make requests and check the responses.
Now I've been tasked with writing a unit and integration test suite so that we can automate our testing going forward. I've been using mocha and now am trying to use supertest for the integration testing. The problem is that supertest expects a server object which it then applies tests to however our file that builds our server object doesn't return anything. I don't want to modify that file so I am stumped as to how to access the server object to use for testing.
My server file looks (in part) like this:
var express = require('express') var app = express(); // Express Configuration app.use(express.favicon()); //handles favicon request, which keeps it out of the log when using a browser :) app.use(express.bodyParser()); //slurps up the body in chunks the node.js way :) // ...and so on
and my mocha test file looks like this
var request = require('supertest') , app = require('../server.js') , assert = require("assert"); describe('POST /', function(){ it('should fail bad img_uri', function(done){ request(app) .post('/') .send({ 'img_uri' : 'foobar' }) .expect(500) .end(function(err, res){ console.dir(err) console.dir(res) done(); }) }) })
when I run this test I get a complaint about the app object not having a method named address. My question is, is there a way I can require/call the server.js file so that the app object will be in scope? Or am I going about this wrong. I also played around a little bit with using http.js to make calls directly to the server but didn't have luck that way either. Thanks!
SuperTest is a Node. js library that helps developers test APIs. It extends another library called superagent, a JavaScript HTTP client for Node. js and the browser. Developers can use SuperTest as a standalone library or with JavaScript testing frameworks like Mocha or Jest.
It is used to test HTTP servers by sending a method like GET, PUT, POST or DELETE, Supertest can test any HTTP requests. Even multipart file uploads like the one my API has.
js/Express. js App Only Works on Port 3000.
You need to export the app
object in server.js
:
var app = express(); module.exports = app; ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With