简体   繁体   English

使用Mocha / chai / sinon进行单元测试Express-如何测试res.send对象的形状?

[英]Unit Testing Express with mocha/chai/sinon - how do I test my res.send object shape?

I am unit testing the individual components that lead up to an API response, in other words, I'm testing it independently of a route since every route runs through this component 我正在对导致API响应的各个组件进行单元测试,换句话说,我正在独立于路由进行测试,因为每条路由都通过该组件运行

I need to test that the function responsible for sending my express response is the correct shape, but without sending an actual HTTP request I can't figure out how to test it. 我需要测试负责发送我的快速响应的函数的形状正确,但是如果没有发送实际的HTTP请求,我将无法弄清楚如何对其进行测试。

Here is my component 这是我的组件

'use strict'

const moment = require('moment')
module.exports = (req, res, payload) => {
  try {
    let data = []
    if (payload.token) data.push({ token: payload.token })
    data.push({ [payload.resource]: payload.data })
    res.send({
      status: 'OK',
      recordCount: payload.data.length,
      startTimestamp: req.start.toDate(),
      endTimestamp: moment().toDate(),
      timeTaken: moment().toDate().getTime() - req.start.toDate().getTime(),
      data: data
    })
  } catch (error) {
    return res.status(500).json({
      errors: [{
        location: 'n/a',
        param: 'n/a',
        msg: 'something happened when generating the response'
      }]
    })
  }
}

here is my current test ... 这是我目前的测试...

const chai = require('chai')
const sinonChai = require('sinon-chai')
const { mockReq, mockRes } = require('sinon-express-mock')
const moment = require('moment')
const present = require('../../src/lib/present')

chai.use(sinonChai)

describe('unit test the present lib method', () => {
  it('should return the expected shape', (done) => {
    const req = mockReq({
      start: moment().toDate(),
      body: {}
    })
    const res = mockRes()
    const shape = present(req, res, {
      resource: 'empty_array',
      data: []
    })
    shape.should.have.own.property('data') // doesnt work
    // AssertionError: expected { Object (append, attachement, ...) } to have own property 'data'
    done()
  })
})

To properly test schema of response you need to do E2E test, which requires you, to send an API call. 要正确测试响应模式,您需要进行E2E测试,这要求您发送API调用。

If you want to test just logic, inside of the route, you can always extract it to some service, and just test this service. 如果您只想测试逻辑,则可以始终将其提取到某个服务中,然后测试该服务。

You can read the following article: https://www.freecodecamp.org/news/how-to-mock-requests-for-unit-testing-in-node-bb5d7865814a/ 您可以阅读以下文章: https : //www.freecodecamp.org/news/how-to-mock-requests-for-unit-testing-in-node-bb5d7865814a/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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