Lukas
Lukas

Reputation: 10360

nock: reply is not a function

I am using nock to intercept my http requests in a mocha / chai environment. Also i am using supertest and supertest-chai to query my own express server. Like this:

import { it } from 'mocha'; import chai, { should } from 'chai';

import request from 'supertest';
import supertestChai from 'supertest-chai';
import Joi from 'joi';
import chaiJoi from 'chai-joi';
// others

function itRespondsTo({ url, response, description, parameters = {} }) {
  const maxAge = parameters.maxAge || serverConfig.defaultCacheAge;
  const params = parameters ? `${Object.entries(parameters).map(([name, val]) => `&${name}=${val}`).join('&')}` : '';
  const path = `/oembed?url=${encodeURIComponent(url)}${params}`;
  const desc = description || `/oembed?url=${url}${params}`;
  it(`should respond to ${desc}`, (done) => {
    request(server)
      .get(path)
      .expect(200)
      .expect('Content-Type', /json/)
      .expect('Access-Control-Allow-Methods', 'GET')
      .expect('Cache-Control', `public, max-age=${maxAge}`)
      .expect(res => Object.values(OEMBED_TYPES).should.include(res.body.type)) // [1]
      .expect(res => Joi.validate(res.body, OEMBED_SCHEMAS[res.body.type]).should.validate)
      .expect(response)
      .end(done);
  });
}

describe('YouTube endpoint', () => {
  beforeEach(() => {
    nock(/youtube\.com/)
      .reply(200, remoteResponse);
  });

  afterEach(() => {
    nock.restore();
  });

  itRespondsTo({ url: 'https://youtu.be/m4hklkGvTGQ', response });
  itRespondsTo({ url: 'https://www.youtube.com/embed/m4hklkGvTGQ', response });
  itRespondsTo({ url: 'https://www.youtube.com/watch?v=m4hklkGvTGQ', response });
  itRespondsTo({ url: 'https://www.youtube.com/?v=m4hklkGvTGQ', response });
});

When I run my tests, the first call of itRespondsTo will always throw an error:

1) YouTube endpoint "before each" hook for "should respond to /oembed?url=https://youtu.be/m4hklkGvTGQ":

TypeError: nock.reply is not a function

And it will always be the first call of itRespondsTo. If I remove the first call, the next call will throw the error and so on. I have no idea why this is happening.

Upvotes: 1

Views: 1176

Answers (1)

Lukas
Lukas

Reputation: 10360

I found the reason I got an error. I had to put a get in between:

nock('https://www.youtube.com')
  .get('/oembed')
  .query(true)
  .reply(200, remoteResponse);

Upvotes: 2

Related Questions