I am learning Node.js and Express framework. I am a big fan of jasmine. So I want to use jasmine whenever I can, however, I can't find a good way testing Express with jasmine. For example, how should I test a route in app.js?
If I have this route in app.js:
app.get('/', function(req, res) { ... });
How can I use jasmine to test it?
Fortunately there exists the npm package jasmine-node which makes Jasmine available for node. js apps as well. You can give jasmine-node a try by running npm install jasmine-node -g . This will install jasmine-node globally, so we're able to run jasmine-node from the command line.
Jasmine can be used as a standalone application where you download the framework and put your JavaScript files inside the src folder. Then you write the test files (often called "specs") and put them in the spec folder.
Since Jasmine 2 it is very simple to use Jasmine in a Node.js environment. To test express apps with it, I recommend to use Jasmine in combination with supertest.
Here is how such a test looks like:
project/spec/ServerSpec.json
const request = require('supertest'); const app = require('../app'); describe('Server', () => { describe('REST API v1', () => { it('returns a JSON payload', (done) => { request(app) .get('/rest/service/v1/categories') .expect(200) .expect('Content-Type', 'application/json; charset=utf-8') .end((error) => (error) ? done.fail(error) : done()); }); }); });
Some prerequisites:
npm i -D jasmine@2
npm i -D supertest@3
jasmine init
(Note: You need to install Jasmine globally first if you haven't done already to run this command)ServerSpec.js
)Here is how a Jasmine configuration looks like:
project/spec/support/jasmine.json
{ "helpers": [ "helpers/**/*.js" ], "random": false, "spec_dir": "spec", "spec_files": [ "**/*[sS]pec.js" ], "stopSpecOnExpectationFailure": false }
To run your specifications (test suites) simply add this to your npm scripts and execute npm test
(or just npm t
):
"scripts": { "test": "jasmine" },
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