request-promise: Mockery doesn't work as expected

Hi,

I’m trying to mock the whole request-promise as in the documentation. But my request still hits the real server. What should I do.

I’m using

"mockery": "^1.4.1",
"request-promise": "^1.0.2",

Here’s my code

    before(function before(done) {
      mockery.enable({
        warnOnReplace: false,
        warnOnUnregistered: false,
        useCleanCache: true
      });

      mockery.registerMock('request-promise', function () {
        var response = '{}';
        console.log('register'); // <-- This doesn't print out.
        return Bluebird.resolve(response.trim());
      });

      done();

    });

    after(function after(done) {
      mockery.disable();
      mockery.deregisterAll();
      done();
    });

This is how I call the test

      var request = {payload: {
        queryType: 'queryType'
      }};

      var expectQuery = {};
      analytics.query(request, function reply(response) {
        var data = response.data;
        var query = response.query;
        console.log(query);
        done();
      });

This is the code inside analytics.query

query: function druid(request, reply) {
    var query = request.payload;
    queries.query(query).then(function thenFunc(response) {
      return reply({
        data: response,
        query: query
      });
    })
    .catch(function catchFunc(err) {
      console.log('error'); // <-- It prints this
      return reply(Boom.notFound(err.error.error, {message: err.error.error}));
    });
  },

The request comes to catch function which I don’t expect it as I thought mockery will catch any request and return resolve?

About this issue

  • Original URL
  • State: open
  • Created 8 years ago
  • Comments: 17 (6 by maintainers)

Most upvoted comments

I’ve tried nock and it works perfectly. This is what I do in my test

afterEach(() => {
  nock.cleanAll();
});

nock('/api')
       .get(`/user`)
       .reply(200, {results: []});

THANK YOU @vaelinn ! 🙏

Yes, it turns out I just needed to “enable” mockery in my tests. doh! 😁

Also, I noticed that this line that calls registerAllowable doesn’t seem to do affect the code execution at all…

mockery.registerAllowable('./callForStuff', true);

I have updated the code in my links above, and it should be working now. Thanks all!