How to mock request and response in nodejs to test middleware/controllers?

后端 未结 6 711
花落未央
花落未央 2021-02-01 14:37

My application has several layers: middleware, controllers, managers. Controllers interface is identical to middlewares one: (req, res, next).

So my question is: how ca

6条回答
  •  暖寄归人
    2021-02-01 15:29

    I would try using dupertest for this. It's a node module I created for the very purpose of easy controller testing without having to spin up a new server.

    It keeps the familiar syntax of node modules like request or supertest, but again, without the need to spin up a server.

    It runs a lot like Hector suggested above, but integrates with a test framework like Jasmine to feel a little more seamless.

    An example relating to your question may look like:

    request(controller.get_user)
      .params({id: user_id})
      .expect(user, done);
    

    Or the more explicit longhand version:

    request(controller.get_user)
      .params({id: user_id})
      .end(function(response) {
        expect(response).toEqual(user);
        done();
      });
    

    Note: the examples assume user_id and user are defined somewhere, and that the controller grabs and returns a user based on id.

    Edit: reading your response to an answer above, I will admit the downside currently is that this module does not integrate a more robust mock request or response object by default. dupertest makes it super easy to extend and add properties to both req and res, but by default they are pretty bare.

提交回复
热议问题