首页 > 解决方案 > 如何使 nock 以“未定义”的身体响应?

问题描述

我正在测试一个处理不同情况的请求处理程序,其中一个需要 HTTP 代码 204 的响应并且没有响应正文 ( typeof response.body === 'undefined')。

我试图将回复设置为nullundefined而根本没有设置它。在所有这些情况下,响应正文都是一个空字符串 ( '')。

有没有办法从 Nock 中删除响应正文?

这是我要运行的测试:

it('should return true if body is undefined (usually, 204 status responses - No content)', async () => {
  nock('http://test.com')
    .put('/')
    .reply(204, undefined)
//  .reply(204, null) also fails
//  .reply(204) also fails

 const result = await Request._request('http://test.com', { method: 'PUT' })

 expect(result).to.be.true
})

这是我要测试的代码:

static async _request (url, options) {
    return new Promise((resolve, reject) => {
      request(url, options)
        .then((response) => {
          if (response.statusCode < 300) {
            if (typeof response.body === 'undefined') {
              resolve(true)
            } else if (isJSON(response.body)) {
              resolve(JSON.parse(response.body.replace(/\s/g, ' ')))
            } else {
              .
              .
              .

标签: javascriptunit-testingnockhttp-status-code-204

解决方案


推荐阅读