question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Does it work with Supertest? Tests fail with `TypeError: Cannot read property 'status' of undefined`

See original GitHub issue

I’ve spent days trying to figure out what I do wrong, checked the docs and issues, but it still fails with:

   TypeError: Cannot read property 'status' of undefined
      
      at Test.Object.<anonymous>.Test._assertStatus (node_modules/supertest/lib/test.js:263:10)
      at Test.Object.<anonymous>.Test._assertFunction (node_modules/supertest/lib/test.js:281:11)
      at Test.Object.<anonymous>.Test.assert (node_modules/supertest/lib/test.js:171:18)
      at assert (node_modules/supertest/lib/test.js:131:12)
      at node_modules/supertest/lib/test.js:128:5
      at Test.Object.<anonymous>.Request.callback (node_modules/superagent/lib/node/index.js:688:3)
      at ErroringClientRequest.<anonymous> (node_modules/superagent/lib/node/index.js:615:10)
      at Object.onceWrapper (events.js:293:19)
      at emitOne (events.js:96:13)
      at ErroringClientRequest.emit (events.js:191:7)
      at ErroringClientRequest.<anonymous> (node_modules/nock/lib/intercept.js:219:10)
      at _combinedTickCallback (internal/process/next_tick.js:73:7)
      at process._tickCallback (internal/process/next_tick.js:104:9)

Does Nock work with Jest/Supertest?

I created an repo to reproduce the issue - https://github.com/rosendi/nock-test

P.S. Tested on Node 7.9.0 and 7.10.0

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
danturucommented, Aug 8, 2017

@sdotson the problem was in Nock Back, so i wrote my own VCR implementation. Don’t remember all the details, but here is code that I use and it works:

vcr.js

import fs from 'fs-extra';
import path from 'path';
import nock from 'nock';

function getCassetePath(testPath) {
  return `${path.dirname(testPath)}/__cassettes__/${path.basename(testPath, path.extname(testPath))}.json.cassette`;
}

function loadCassette(cassetePath) {
  const defs = nock.loadDefs(cassetePath);

  defs.forEach((def) => {
    def.options = def.options || {};

    def.options.filteringScope = (scope) => (
      !(/127.0.0.1/.test(scope))
    );
  });

  return nock.define(defs);
}

function vcr({ testPath, recordMode = 'dryrun' } = {}) {
  const cassettePath = getCassetePath(testPath);

  let recording;

  beforeAll(() => {
    recording = false;

    nock.restore();

    switch (recordMode) {
      case 'dryrun': {
        if (fs.pathExistsSync(cassettePath)) {
          loadCassette(cassettePath);
        }

        break;
      }

      case 'record': {
        if (fs.pathExistsSync(cassettePath)) {
          nock.enableNetConnect(/127.0.0.1/);

          loadCassette(cassettePath);
        } else {
          nock.recorder.clear();
          nock.recorder.rec({ dont_print: true, output_objects: true });

          recording = true;
        }

        break;
      }

      default:
        throw new Error(`Unsupported record mode "${record}".`);
    }
  })

  afterAll(() => {
    if (recordMode === 'record' && recording) {
      fs.outputFileSync(cassettePath, JSON.stringify(nock.recorder.play(), null, 2));
    }

    nock.restore();
  });
}

export default vcr;

Test example (PlansController fetches data from Stripe):

import request, { json } from 'test/request';
import vcr from 'test/vcr';

describe('PlansController', () => {
  vcr({ testPath: __filename, recordMode: 'record' });

  test('displays a list of the avaiable plans', async () => {
    const { body } = await json(request.get('/api/v1/plans')).expect(200);

    expect(body).toMatchSnapshot();
  });
});

The request variable is const request = supertest(app.listen());

If you have a repo, I could check it.

0reactions
lock[bot]commented, Oct 6, 2018

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue and add a reference to this one if it’s related. Thank you!

Read more comments on GitHub >

github_iconTop Results From Across the Web

supertest TypeError: Cannot read properties of undefined ...
Try to execute a one-time setup. closing and re-opening the connection after every test might be the cause of the issue:
Read more >
Supertest - npm
SuperTest works with any test framework, here is an example without using any test framework at all: const request = require('supertest'); ...
Read more >
How to test a post request for fetching the result in javascript ...
You might need to look at the documentation for the API endpoint and see why it's producing an incompatible response. Your code is...
Read more >
Writing API Tests with Jest - Rithm School
Since we are using testing libraries, these are not dependencies that will be using in production. Therefore, when we install these using npm...
Read more >
How to Test Nodejs Code and RESTful API - CodeForGeek
Getting below error after .double callback warning. Uncaught TypeError: Cannot read property 'status' of undefined. Anthony Jackman.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found