gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:48 25 4
gpt4 key购买 nike

我正在对导致 API 响应的各个组件进行单元测试,换句话说,我正在独立于路由进行测试,因为每个路由都经过此组件

我需要测试负责发送快速响应的函数的形状是否正确,但如果不发送实际的 HTTP 请求,我无法弄清楚如何测试它。

这是我的组件

'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'
}]
})
}
}

这是我当前的测试...

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()
})
})

最佳答案

要正确测试响应模式,您需要进行 E2E 测试,这需要您发送 API 调用。

如果您只想测试路由内部的逻辑,您始终可以将其提取到某个服务,然后只测试该服务。

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

关于node.js - 使用 mocha/chai/sinon 进行单元测试 Express - 如何测试我的 res.send 对象形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56471968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com