如何为NodeJS单元测试模拟request-promise-native?

时间:2017-10-09 21:58:45

标签: node.js unit-testing sinon ava

我的NodeJS应用程序使用request-promise-native。

import request from 'request-promise-native'
const https = require('https')

const myRequest = request.defaults({
  baseUrl: 'myBaseUrl',
  agent: new https.Agent({ keepAlive: true })
})

async function findResults() {
  const myResponse = await myRequest.get({
      uri: '/myUri'
  })
  return myResponse
}

我正试图模仿'获得'上述单元测试请求。但它仍然会进行实际调用并获得结果,而不是通过我的模拟对象调用。

我使用Sinon尝试了不同的变体:

import test from 'ava'
import sinon from 'sinon'
import Bluebird from 'bluebird'
import request from 'request-promise-native'
import { findResults } from '../services/results'

test.only(async t => {
  let response = JSON.stringify({
     statusCode: 504
  })

  sinon.stub(request, 'get').returns(Bluebird.resolve(response))

  const returnValue = await findResults()
  console.log('return: ', returnValue)

  t.is (1, 1)
})

使用Mockery(根据文档https://www.npmjs.com/package/request-promise

import mockery from 'mockery'
import { findResults } from '../services/results'

test.before(async t => {
    mockery.enable({
      warnOnReplace: false,
      warnOnUnregistered: false,
      useCleanCache: true
    })

  mockery.registerMock('request-promise-native', function () {
  // var response = fs.readFileSync(__dirname + '/data/' + filename, 'utf8');
    let response = JSON.stringify({
        statusCode: 9
    })
   return Bluebird.resolve(response.trim());
  })
})

test.after(async t => {
   mockery.disable()
   mockery.deregisterAll()
   // done()
})

test.only(async t => {
   const returnValue = await findResults()
   console.log('return: ', returnValue)

   t.is(1, 1)
})

我也试过了proxyquire和sinon的假服务器的变种。但我无法让他们工作。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

通常,如果在导入的包上使用sinon spy,您可以像sinon.spy(request.prototype, 'get')那样创建存根。这在这里不起作用,大概是因为请求没有定义原型上的方法。解决这个问题的一种方法是在实例上创建存根(如果你可以调用它)。示例如下:

const request = require( 'request-promise-native')
const https = require('https')
const {expect} = require('chai')
require('mocha')
const sinon = require('sinon')
const Bluebird = require( 'bluebird')

const myRequest = request.defaults({
  baseUrl: 'myBaseUrl',
  agent: new https.Agent({ keepAlive: true })
})

async function findResults() {
  const myResponse = await myRequest.get({
      uri: '/myUri'
  })
  return myResponse
}



async function mainTest() {
  let response = JSON.stringify({
     statusCode: 504
  })
  sinon.stub(myRequest, 'get').callsFake((params) => Bluebird.resolve(response))
  const returnValue = await findResults()
  console.log('return: ', returnValue)
}

mainTest()

答案 1 :(得分:0)

我使用了proxyquire。以下是我用来模拟请求承诺的一些代码:

const proxyquire = require('proxyquire');
before(function (done) {

        rpMock = function () {
            var response = generateFakeResponse();
            return Bluebird.resolve(response.trim());
        };

        done();
    });

    // actual test:
    it('tests my function', function () {
         let MyModule = proxyquire('./MyModule',{'request-promise':rpMock});
         let myModuleObj = new MyModule();
    }