【问题标题】:Nock: nock.load does not work as expectedNock:nock.load 没有按预期工作
【发布时间】:2023-07-10 05:05:02
【问题描述】:

我正在尝试使用 Nock 函数加载包含模拟响应的 JSON 文件:nock.load(filePath)。奇怪的是,测试失败并出现错误:

TypeError: nockDefs.forEach 不是函数

如果我用原始 JSON 替换 nock.load 调用,测试运行良好。这是我的测试代码:

describe('Sample description', function () {

  it('sample desc', function () {
    this.timeout(0);
    nock("https://sample.url.com")
    .get('/endpoint')
    .reply(200, nock.load('tests/responses/get_response_200.json'));

    return api
      .getResponse()
      .then(res => expect(res).to.be({
          first_name: "Ada",
          last_name: "Obi"
      }
   ));

  })
})

我已验证我的 JSON 文件包含有效的 JSON,我什至尝试过使用更简单的 JSON 结构,但相同的错误消息仍然存在。

我目前使用的是最新版本的 nock:13.1.0。这种行为的原因可能是什么?

【问题讨论】:

    标签: javascript unit-testing nock


    【解决方案1】:

    nock.load 用于导入记录的 Nock 响应,不加载任意 JSON。

    你要的是.replyWithFile():

    nock("https://sample.url.com")
      .get('/endpoint')
      .replyWithFile(200, 'tests/responses/get_response_200.json')
    

    或者,您可以自己加载和解析 JSON,使用 require()JSON.parse(fs.readFileSync('tests/responses/get_response_200.json', 'utf-8'))

    【讨论】: