0

I am wiring jasmine test cases for one of the application. I have just started learning jasmine. Below is my script code

var aclChecker = function(app,config) {

    validateResourceAccess = function (req, res, next) {
            req.callanotherMethod();
            res.send(401,'this is aerror message');
   }

}

Now i want to spyOn res and req object to know if send method has been called. As req and res are not global variables i am having this doubt on how to create a spy on in junit spec

Please help!!!!!!!!

Punith Raj
  • 2,164
  • 3
  • 27
  • 45

2 Answers2

4

You can simply mock req and res like this.

  describe("acl checker", function() {
    it("should validate resource access", function() {
      var mockReq = {
          callAnotherMethod: function() {}
      };
      var mockRes = {
        send: function() {}
      };
      var mockNext = {};
      spyOn(mockReq, "callAnotherMethod");
      spyOn(mockRes, "send");

      aclChecker.validateResourceAccess(mockReq, mockRes, mockNext);
      expect(req.callAnotherMethod).toHaveBeenCalled();
      expect(res.send).toHaveBeenCalledWith(401, 'this is aerror message');
    });
  });
Srivathsa
  • 941
  • 1
  • 10
  • 27
1

Typically, in a unit test you would mock any resource requests and only validate that the request is proper. So you would instead call a mock request library, and validate that the url and headers are correct.

However, if you really want to test the actual access to the resource, you will need to build your request object first, and give yourself access to it afterwards.

If you want to learn about request mocking, check out jasmine-ajax: https://github.com/pivotal/jasmine-ajax

If you still want to do this, you should use a beforeEach function in the test file to create the dependencies you need for your tests.

Take a look at this for more help with beforeEach: https://github.com/pivotal/jasmine/wiki/Before-and-After

Olivercodes
  • 1,048
  • 5
  • 17