简体   繁体   中英

Node.js - Mock result of a promise

I want to mock the result of a function within a node module so that i can run assertions. Considering the following node module:

const doPostRequest = require('./doPostRequest.js').doPostRequest;
const normalizeSucessResult = require('./normalizer.js').normalizeSucessResult;
const normalizeErrorResult = require('./normalizer.js').normalizeErrorResult;

exports.doPost = (params, postData) => {
  return doPostRequest(params, postData).then((res) => {
    const normalizedSuccessResult = normalizeSucessResult(res);
    return normalizedSuccessResult;
  }).catch((err) => {
    const normalizedErrorResult = normalizeErrorResult(err);
    return normalizedErrorResult;
  })
}

The function doPostRequest returns a promise. How can i fake the return value of this promise so that i can assert if normalizeSucessResult has been called? So for i have tried:

const normalizeSucessResult = require('./normalizer.js');
const doPostRequest = require('./doPostRequests.js');
const doPost = require('./doPost.js');

it('runs a happy flow scenario', async () => {
  let normalizeSucessResultStub = sinon.stub(normalizeSucessResult, 'normalizeSucessResult');
  let postData = { body: 'Lorum ipsum' };
  let params = { host: 'someUrl', port: 433, method: 'POST', path: '/' };

  sinon.stub(doPostRequest, 'doPostRequest').resolves("some response data"); //Fake response from doPostRequest

  return doPost.doPost(params, postData).then((res) => { //res should be equal to some response data
    expect(normalizeSucessResultStub).to.have.been.calledOnce;
    expect(normalizeSucessResultStub).to.have.been.with("some response data");
  });
});

The doPostRequest module looks like this:

const https = require('https')
 module.exports.doPostRequest = function (params, postData) {
  return new Promise((resolve, reject) => {
    const req = https.request(params, (res) => {
      let body = []
      res.on('data', (chunk) => {
        body.push(chunk)
      })
      res.on('end', () => {
        try {
          body = JSON.parse(Buffer.concat(body).toString())
        } catch (e) {
          reject(e)
        }
        resolve(body)
      })
    })
    req.on('error', (err) => {
      reject(err)
    })
    if (postData) {
      req.write(JSON.stringify(postData))
    }
    req.end()
  })
}

您可以使用Promise.resolve返回具有任何给定值的Promise

Promise.resolve(“hello world”);

对于存根您的功能,您需要这样做

sinon.stub({doPostRequest}, 'doPostRequest').resolves("some response data")

Okay, i figured it out. The function doPostRequest was loaded using require , on the top of the file using const doPostRequest = require('./doPostRequest.js').doPostRequest;

In order to mock the data that comes back from a function that is loaded using require i had to use a node module called mock-require . There are more modules that can take care of this ( proxyquire is a populair one) but i picked mock-require (i did not have a specific reason for choosing mock-require).

For anyone else that is stuck with a similar problem, try mock-require to mock the respose from files that are loaded using require .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM