Use jasmine to test Express.js

寵の児 提交于 2019-12-02 22:12:28

Jasmine-node makes it easy to use jasmine with node.js. There are some examples on their site. Another example can be found from http://blog.drewolson.org/post/14684497867/ web.archive.org

You should try out http://frisbyjs.com/

I haven't had a chance to use it, but as I was looking for a solution to the same problem, this was the best I could find.

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:

  1. Install Jasmine v2 as dev dependency in your project: npm i -D jasmine@2
  2. Install supertest v3 as dev dependency in your project: npm i -D supertest@3
  3. Create an initial Jasmine configuration using jasmine init (Note: You need to install Jasmine globally first if you haven't done already to run this command)
  4. Create a specification ending on "Spec.js" (like 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"
  },

You can use supertest with jasmine but you'll just need to manually pass errors. An issue on GitHub project was opened about this a while ago.

https://github.com/jasmine/jasmine-npm/issues/31

You can try using supertest-as-promised with Jasmine. It is working for me: https://github.com/WhoopInc/supertest-as-promised

Here are some examples:

Maybe you could try supertest with mocha.

Here's a simple example :

var request = require('supertest')
  , express = require('express');

var app = express();

app.get('/user', function(req, res){
  res.send(200, { name: 'toto' });
});


describe('GET /user', function(){
  it('should respond with json', function(done){
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', 'json')
      .expect(200, done);
  })
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!