How does one unit test routes with Express?

后端 未结 8 2181
一整个雨季
一整个雨季 2020-12-07 08:38

I\'m in the process of learning Node.js and have been playing around with Express. Really like the framework;however, I\'m having trouble figuring out how to write a unit/i

8条回答
  •  星月不相逢
    2020-12-07 09:35

    As others have recommended in comments, it looks like the canonical way to test Express controllers is through supertest.

    An example test might look like this:

    describe('GET /users', function(){
      it('respond with json', function(done){
        request(app)
          .get('/users')
          .set('Accept', 'application/json')
          .expect(200)
          .end(function(err, res){
            if (err) return done(err);
            done()
          });
      })
    });
    

    Upside: you can test your entire stack in one go.

    Downside: it feels and acts a bit like integration testing.

提交回复
热议问题