Node TAP 18.7.0

tap Nock Plugin (optional)

@tapjs/nock

A tap extension that integrates nock.

Features#

Usage#

Load the @tapjs/nock plugin in your tap config.

For example, in .taprc:

plugins:
  - @tapjs/nock

Or in package.json:

{
  "tap": {
    "plugins": ["@tapjs/nock"]
  }
}

Then use it in your tests like so:

import t from 'tap'

t.test('sends a request', async t => {
  t.nock('https://registry.npmjs.org')
    .get('/')
    .reply(200, { hello: 'world' })

  const res = await fetch('https://registry.npmjs.org')
  t.equal(res.status, 200)
  const body = await res.json()
  t.same(body, { hello: 'world' })
})

// when snapshots are enabled, this test will send a real request
// and record the response
// when they are disabled, the recorded response will be
// automatically loaded into a nock scope, and the test will
// receive that response
// This requires that the @tapjs/snapshot plugin is enabled.
t.test('snapshots a request', async t => {
  t.nock.snapshot()

  const res = await fetch('https://registry.npmjs.org')
  t.equal(res.status, 200)
  const body = await res.json()
  t.match(body, { db_name: 'registry' })
})

You may use it directly, though that is a bit more clunky, because it won't be automatically applied to child tests, but it can be good if you only need nock in a small number of tests.

import tapNock from '@tapjs/nock'
import t from 'tap'

t.test('sends a request', async t => {
  const tn = tapNock(t)
  tn.nock('https://registry.npmjs.org')
    .get('/')
    .reply(200, { hello: 'world' })

  const res = await fetch('https://registry.npmjs.org')
  t.equal(res.status, 200)
  const body = await res.json()
  t.same(body, { hello: 'world' })
})

// when snapshots are enabled, this test will send a real request
// and record the response
// when they are disabled, the recorded response will be
// automatically loaded into a nock scope, and the test will
// receive that response
// This requires that the @tapjs/snapshot plugin is enabled.
t.test('snapshots a request', async t => {
  const tn = tapNock(t)
  tn.nock.snapshot()

  const res = await fetch('https://registry.npmjs.org')
  t.equal(res.status, 200)
  const body = await res.json()
  t.match(body, { db_name: 'registry' })
})

Credits#

This plugin was originally developed by nlf as the standalone extension @npmcli/tap-nock, and the use case was a major inspiration for tap's plugin eventual architecture.