使用proxyquire和sinon测试ExpressJS

时间:2018-08-01 12:29:12

标签: express sinon proxyquire

TL; DR

如何使用proxyquireexpress.Router()中的函数调用替换为sinon.stub()


我有一个expressJS服务器

import express from 'express'
import serverIndex from './server/index'

const app = express()

app.set('port', (process.env.PORT || 3001))

app.use((req, res, next) => {
  serverIndex(req, res, next)
})

app.listen(app.get('port'), () => {
  logger.info(`Find the server at: http://localhost:${app.get('port')}/`) // eslint-disable-line no-console
})

module.exports = app

我将路线分为一个单独的文件:

import express from 'express'
import {
  externalFunction
} from './serverHelper'

const router = express.Router()

router.get(`${publicPath}/api/callMe`, (req, res) => {
  externalFunction()
    .then(response => res.send(response))
    .catch(error => res.status(400).send({ error: error.message }))
})

export default router

现在,我想测试调用函数时服务器是否返回正确的HTTP状态和主体。我已经测试过serverHelper,现在我只想确保在进行集成测试之前,我也涵盖了所有路由,并且单元测试正在运行。

我的问题是我无法与proxyquire和sinon一起表达用残存的响应替换对serverHelper的调用

import sinon from 'sinon'
import request from 'supertest'
import proxyquire from 'proxyquire'

describe('server unit Test', () => {
  it('should do test', async () => {
    const proxyquireStrict = proxyquire.noCallThru()
    const stubbed = proxyquireStrict('../../../server', {
      './server/index': {
          externalFunction: sinon.stub().resolves({ message: 'Wohoo' })
        }
    })

    const response = await request(stubbed).get('/api/callMe')
    console.log(response)
  })
})

这总是失败,TypeError: (0 , _index2.default) is not a function

0 个答案:

没有答案