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.

Nock back not using records

See original GitHub issue

I’m trying to record some Stripe HTTP calls happening on the background of executing Stripe’s node library.

I rooted for nock’s back feature however I’m not having best results while trying to execute it with 'record' mode.

What is happening:

  • A fixture file is created if ran first with record mode. This includes 3 requests:
    • Corresponds to the call to Stripe API the library initiates for customer creation.
    • Second one is the call to Stripe API for subscription cereation
    • The third one is a hit to our API endpoint which actually causes the previous calls get executed.
  • On the second and any consecutive execution of the tests, the response to my endpoint would end with null response.

This is the code snippet relevant to the usage of nock:

nockBack.fixtures = path.join(__dirname, 'fixtures')
nockBack.setMode('record')

describe.only('Subscriptions creation', function () {
  this.timeout(20000)

  before(function (done) {
    let {user, jwt} = getRandomUserAndJwt()
    testToken = jwt
    return setupTestDatabaseWithUser(user, async function (err, createdUser) {
      if (err) return done(err)
      testUser = createdUser
      const { nockDone } = await nockBack('subscription.json')
      chai.request(server)
      .post(API_BASE)
      .set('Authorization', `Bearer ${testToken}`)
      .send(testRequestPayload)
      .end(function (err, response) {
        const {status, body: subscription} = response
        status.should.equal(201)
        should.exist(subscription)
        const nyaFields = ['id', 'status', 'planId', 'stripe_status', 'dateSubscriptionWillRenew']
        nyaFields.forEach(f => subscription.should.haveOwnProperty)
        testSubscription = subscription
        nockDone()
        nockBack.setMode('wild')
        done(err)
      })
    })
  })

So

    const { nockDone } = await nockBack('subscription.json')

causes a file to be created. I repeat, it’s an array with 3 requests happening.

If I execute again,

    .end(function (err, response) {

err will be defined and telling:

{ NetConnectNotAllowedError: Nock: Not allow net connect for "127.0.0.1:63304/api/subscriptions" (...)
  name: 'NetConnectNotAllowedError',
  code: 'ENETUNREACH',
  message: 'Nock: Not allow net connect for "127.0.0.1:63304/api/subscriptions"',
  response: undefined }

So I tried adding

  nock.disableNetConnect()
  nock.enableNetConnect(/127\.0\.0\.1/)

before recording and also making sure at the end of the hook, nock set ups would look like:

    nockDone()
    nockBack.setMode('wild')
    nock.cleanAll()
    nock.enableNetConnect()

But still haveing same issues

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:4
  • Comments:10 (2 by maintainers)

github_iconTop GitHub Comments

6reactions
bohachevskyycommented, Oct 25, 2018

Hello @benplummer @diegoaguilar please try to call nock.enableNetConnect();after nockDone initialization. It allows me to call localhost:

const { nockDone } = await nockBack('subscription.json')
nock.enableNetConnect(/127\.0\.0\.1/);

But there s another issue here: fixture contains timestamp in a request. The timestamp will be different each request, and fixture won’t correspond.

I tried to modify timestamp in before func that passed as an option to nockBack, but didn’t manage to do that.

Will be happy to hear any help 😃

1reaction
bmitchinsoncommented, Feb 25, 2021

destructoring nockDone and saving it to call later worked great for me

    // Not to be utilized in committed code, only for local dev + recording fixtures
    //   Fixtures are then committed
    @given(/I am recording to "(.*)"/)
     public async startRecording(fixtureLocation: string) {
        nock.back.setMode("record")
        const { nockDone } = await nock.back(`${fixtureLocation}.json`, {
            // Don't mock requests made locally
            afterRecord: defs => defs.filter(def => !def.scope.includes("127.0.0.1"))
        })
        this.saveRecording = nockDone
    }

    @given(/I am done recording/)
    public async stopRecording() {
        if (!this.saveRecording)
            throw new Error(
                "You tried to end a recording that never began. Use startRecording prior to stopRecording."
            )
        else this.saveRecording()
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

nockBack fails to record any fixtures - node.js - Stack Overflow
I do set the back.fixtures option. There is no recording in the fixtures directory and none is created without the nock.restore() call. With...
Read more >
Why did Nock not record all the api requests? | BytesMatter
We ran into an issue where Nock wasn't recording api calls to a new service dependency we introduced into the BytesMatter codebase. The...
Read more >
nock - npm
Start using nock in your project by running `npm i nock`. ... Query Object // return true for matched // return false for...
Read more >
How to use the nock.emitter function in nock - Snyk
nockScope = nock(endpoint, { encodedQueryParams: true }) this.recording = record if (record) ... for tests using nock without this module nock.emitter.
Read more >
nock: disallowed net connect - You.com | The search engine you ...
Is failing for me with: NetConnectNotAllowedError: Nock: Disallowed net connect for "mailer.com:443/send" ... nock/nockNock back not using records#1206.
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