如何 return 无效缓冲区以测试 API 调用?

How to return a invalid Buffer in order to test an API call?

我目前正在学习如何在 Node.js 中编写单元测试。为此,我制作了一个可以进行 API 调用的小文件:

const https = require('https')
module.exports.doARequest = 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) //How can i test if the promise rejects here?
        }
        resolve(body)
      })
    })
    req.end()
  })
}

为了测试这个文件的流畅性,我使用 nock 伪造了一个请求。但是我想测试 JSON.parse 是否抛出错误。 为此,我认为我必须伪造 Buffer.concat(body).toString() 中的数据。假数据应该是 JSON.parse 无法解析的。这样我就可以测试承诺是否被拒绝。唯一的问题是,我该怎么做?

上面doARequest模块对应的测试文件:

const chai = require('chai');
const nock = require('nock');
const expect = chai.expect;

const doARequest = require('../doARequest.js');

describe('The setParams function ', function () {
  beforeEach(() => {
    nock('https://whosebug.com').get('/').reply(200, { message: true })
  });

  it('Goes trough the happy flow', async () => {
    return doARequest.doARequest('https://whosebug.com/').then((res) => {
      expect(res.message).to.be.equal(true)
    });
  });

  it('Rejects when there is an error in JSON.parse', async () => {
    //How can i test this part?
  });
});

任何 help/suggestions 将不胜感激。

现在您正在使用诺克的 shorthand 传回一个对象,即这一行:

nock('https://whosebug.com').get('/').reply(200, { message: true });

相当于传回一个JSON字符串,或者:

nock('https://whosebug.com').get('/').reply(200, JSON.stringify({
    message: true
}));

要强制 JSON.parse 失败,只需传回一个 无效 JSON 的字符串,例如:

nock('https://whosebug.com').get('/').reply(200, 'bad');