Use jasmine to test Express.js

前端 未结 6 588
庸人自扰
庸人自扰 2021-02-04 01:06

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.

6条回答
  •  梦谈多话
    2021-02-04 01:27

    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"
      },
    

提交回复
热议问题