首页 > 解决方案 > 如何返回无效缓冲区以测试 API 调用?

问题描述

我目前正在学习如何在 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://stackoverflow.com').get('/').reply(200, { message: true })
  });

  it('Goes trough the happy flow', async () => {
    return doARequest.doARequest('https://stackoverflow.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?
  });
});

任何帮助/建议将不胜感激。

标签: node.jsunit-testingnock

解决方案


现在你正在使用 nock 的简写来传回一个对象,即这一行:

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

这与传回 JSON 字符串相同,或者:

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

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

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

推荐阅读