Using Nock for the same URLs for multiple tests fails

551 Views Asked by At

I am trying to test the same URLs for multiple types of tests. It works individually but not together. I am aware of the fact that the interceptor for that specific URL is removed once it's used so I used the persist() method so that does not happen. But that doesn't seem to do much of anything? I also tried adding the Nock code for each individual code also but that's not helped. Any help please? :O

import request from 'supertest';
import { assert } from 'chai';
import app from 'app';
import rawResponse from './raw-json-response';
import tokenResponse from './token-response';
const request2 = request(app);
const config = require('config');
const nock = require('nock');
const isJsonTest = function (json) {
  let str = '';
  str = json.toString();
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
};
describe('API', () => {
  beforeEach((done) => {
    if (!nock.isActive()) nock.activate();
    nock('https://login.salesforce.com:443/services/oauth2/token').persist().log(console.log).post('').reply(200, tokenResponse);
    nock(/cloudforce\.com/).persist().log(console.log).get(/\/services\/data\/v41\.0\/query\?q/gm).reply(200, rawResponse);
    done();
  });
  afterEach((done) => {
    nock.cleanAll();
    nock.restore();
    done();
  });
  it('Make sure Nock mock data is pulling through.', (done) => {
    request2.get('/careers-svc/api/vacancies?limit=1').set('Accept', 'application/json').then((response) => {
      assert.equal(JSON.parse(response.text)[0].MF_Location__c, 'The Shard London Bridge', 'Checking if Nock mock data is correct.');
      done();
    });
  });
  it('Vacancies API response is valid JSON', (done) => {
    request2.get('/careers-svc/api/vacancies?limit=1').set('Accept', 'application/json').then((response) => {
      console.log('response: ');
      console.log(response.text);
      const isJson = isJsonTest(response.text);
      assert.isTrue(isJson, 'is valid JSON.');
      done();
    });
  });
0

There are 0 best solutions below