I am trying to load a JSON file that contains a mock response with the Nock function: nock.load(filePath)
. Oddly, the test fails with error:
TypeError: nockDefs.forEach is not a function
If I replace the nock.load
call with raw JSON, the test runs fine. This is my test code:
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"
}
));
})
})
I have verified that my JSON file contains valid JSON and I've even tried experimenting with simpler JSON structures but the same error message persists.
I am using the latest version of nock at this time: 13.1.0. What could be the reason for this behaviour?
nock.load
is for importing recorded Nock responses, not loading arbitrary JSON.
What you want is .replyWithFile()
:
nock("https://sample.url.com")
.get('/endpoint')
.replyWithFile(200, 'tests/responses/get_response_200.json')
Or, you can load and parse the JSON yourself, either using require()
or JSON.parse(fs.readFileSync('tests/responses/get_response_200.json', 'utf-8'))
.