npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mock-turtle-soup

v1.2.0

Published

Wrapper for mocking external services with Nock.

Downloads

4

Readme

mock-turtle-soup

Wrapper for mocking external services with Nock.

NPM Version Linux Build

Install

$ npm install --save-dev mock-turtle-soup

Example usage

Mocking

Basic mocking usage

import { MockTurtle } from 'mock-turtle-soup'
import nock from 'nock'

describe('TestSuite', () => {
  let mockTurtle: MockTurtle
  beforeEach(() => {
    mockTurtle = new MockTurtle(nock, {
      host: 'http://www.google.com'
    })
    mockTurtle.disableExternalCalls()
  })
  afterEach(() => {
    mockTurtle.reset()
  })

  it('mock GET endpoint without parameters', async () => {
    mockTurtle.mockGet('/', { result: 'Soup is ready.' })
    const response = await request.get('www.google.com')
    expect(response.body).toEqual({ result: 'Soup is ready.' })
  })

  it('mock GET endpoint for any parameters', async () => {
    mockTurtle.mockGet('/', { result: 'Some soup is ready.' }, { anyParams: true })
    const response = await request.get('www.google.com').query({
      soupColour: 'red'
    })
    expect(response.body).toEqual({ result: 'Some soup is ready.' })
  })

    it('mock GET endpoint with parameters', async () => {
      mockTurtle.mockGet(
        '/',
        { result: 'Red soup is ready.' },
        {
          requestQuery: {
            soupColour: 'red'
          }
        }
      )

      mockTurtle.mockGet(
        '/',
        { result: 'Green soup is ready.' },
        {
          requestQuery: {
            soupColour: 'green'
          }
        }
      )

      const responseRed = await request.get('www.google.com').query({
        soupColour: 'red'
      })
      expect(responseRed.body).toEqual({ result: 'Red soup is ready.' })

      const responseGreen = await request.get('www.google.com').query({
        soupColour: 'green'
      })
      expect(responseGreen.body).toEqual({ result: 'Green soup is ready.' })
    })

Mocking configuration

MockTurtle constructor accepts following parameters:

  • nock -> instance of nock. Usually retrieved by calling import * as nock from 'nock' or 'const nock = require('nock)'
  • optionDefaults?: GlobalOptions -> optional helper configuration

GlobalOptions parameters:

  • host: string | RegExp | Url -> host path to service being mocked. It may be convenient to use single instance of MockTurtle to mock all endpoints of a single external service.
  • delayConnection?: number -> delay in returning response to mocked endpoint
  • times?: number -> how many times should same response be repeated. By default mock is reused indefinitely
  • nockOptions?: nock.Options -> options that will be passed to nock instance directly
  • allowProtocolOmission?: boolean -> do not throw an error when mocked host does not begin with 'http' (which usually results in mocking not working)
  • allowSlashOmission?: boolean -> do not throw an error when mocked path does not begin with '/' (which usually results in mocking not working)

All these parameters can also be overriden for each mock separately

To mock an endpoint, use mockGet or mockPost methods on MockTurtle instance accordingly. Parameters for these methods:

  • endpointPath: string | RegExp | ((uri: string) => boolean) -> endpoint url. Gets concatenated with MockTurtle host
  • mockedResponse?: EndpointResponse, -> mocked response that will be returned by the mocked endpoint
  • endpointOptions?: EndpointOptions, -> filters to apply when matching call to endpoint with specific mocks
  • optionOverrides?: GlobalOptions -> overrides for MockTurtle options

EndpointOptions parameters:

  • anyParams?: boolean -> if true, any call to specified endpoint will match this mock.
  • requestQuery?: nockNamespace.RequestBodyMatcher -> only matches mock for requests with given query parameters
  • requestBody?: nockNamespace.RequestBodyMatcher -> only matches mock for requests with given body

Response mock generation

Basic mock generation usage

import { ResponseTypescriptExporter } from 'mock-turtle-soup'

const exporter = new ResponseTypescriptExporter(__dirname + '/nock-responses')

describe('ResponseExporter', () => {
  it('Export only response body', async () => {
    const response = await request.get('https://jsonplaceholder.typicode.com/todos/1').set({
      'Accept-Encoding': 'identity' // This will prevent responses from being compressed which is preferred for mock recording
      })
    await exporter.exportResponseBody('todoMock', response)
    })

  it('Export full response with headers and status code', async () => {
    const response = await request.get('https://jsonplaceholder.typicode.com/todos/1').set({
      'Accept-Encoding': 'identity' // This will prevent responses from being compressed which is preferred for mock recording
      })
    await exporter.exportFullResponse('todoFullMock', response)
    })
  })
})