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

server-mocker

v1.6.3

Published

mocking http server for acceptance tests

Downloads

5

Readme

server-mocker

Create a mocked http server for your webapp tests and development

Install

If you use npm:

npm install --save-dev server-mocker

If you use yarn:

yarn add --dev server-mocker

Examples

Testing

You have a webapp with the following code:

export const getUserData = (userId) =>
  fetch(`http://localhost:5000/user?id=${userId}`).then((res) => res.json());

You want to write a test for that code and you need to mock the server response. You can use server-mocker

import {getUserData} from '../api';
import {createServer, json} from 'server-mocker';

const mockingServer = createServer({port: 5000});

const requestUser = (expectedUserId) => (request) =>
  request.urlPath === '/user' && urlParams.id === expectedUserId;

test('getUserData', async () => {
  const userId = 'any_user_id';
  const userData = {
    name: 'Abel',
  };

  mockingServer.stub(requestUser(userId)).returns(json(userData));

  const userData = await getUserData(userId);

  expect(userData.name).toBe('Abel');
});

Dev api server

You can also use server-mocker as a development api server running a small node script:

dev-api.js

import {createServer, json} from 'server-mocker';

const mockingServer = createServer({port: 5000});

const requestUser = (request) => request.urlPath === '/user';

mockingServer.stub(user()).returns(
  json({
    name: 'Abel',
  })
);
node dev-api.js

In your application you can change your api endpoint depending on process.env.NODE_ENV

const API_ENDPOINT =
  process.env.NODE_ENV === 'production' ? 'http://my-real-api.com/' : 'http://localhost:5000';

export const getUserData = (userId) => fetch(`${API_ENDPOINT}/user?id=${userId}`).then((res) => res.json());

API

createServer(options)

Creates an http(s) server instance where you can mock/stub responses

Parameters

  • options: Object
    • port?: number the server will run in this port. If not provided, the server will use a random available port. You can then read it with server.port
    • ssl?: Object you can pase an object with ssl options to use https. When not specified, the server will use http
    • onResponseNotFound?: (r: Request) => mixed You can specify a listener to be called when a the server receives a server which doesn't know how to reply to.

Returns: MockingServer

Examples

const mockingServer = createServer();

using a given port:

const mockingServer = createServer({port: 5000});

with ssl:

const mockingServer = createServer({
  port: 5000,
  ssl: {
    key: fs.readFileSync(__dirname + '/server.key'),
    cert: fs.readFileSync(__dirname + '/server.crt'),
  },
});

MokingServer

.stub(predicate)

Configures a stubbed response for the requests that match the given predicate

Parameters

Returns: Object with key:

Example

import {createServer, text} from 'server-mocker';

const mockingServer = createServer({port: 5000});

// A request predicate wich matches when url has the expected params
const withUrlParams = (expectedUrlParams) => (request) =>
  Object.keys(expectedUrlParams).every(
    (paramName) => request.urlParams[paramName] === expectedUrlParams[paramName]
  );

// Stub the server to return the text "pong" when a request with ?message=ping is received
mockingServer.stub(witUrlParams({message: 'ping'})).returns(text('pong'));

.mock(predicate)

Similar to .stub, the difference is you can make expectations for received requests

Parameters

Returns: Object with key:

Example

const mock = mockingServer.mock(witUrlParams({message: 'ping'})).returns(text('pong'));

.mockImplementation(predicate, fn)

If you need more control, you can use mockImplementation, instead of providing a return value, you provide a function that is called with the matching request and should return a response.

Parameters

Returns: Stub

Example

mockingServer.mockImplementation(witUrlParams({message: 'ping'}), (request) => {
  return text(String(Math.random()));
});

.clearAll()

Removes all the stubs and mocks from the server.

Example

mockingServer.clearAll();

.close()

Removes all the stubs and mocks from the server and closes the server connection.

Example

mockingServer.close();

.port

(number) the server port.

Stub

A Stub (returned by .stub().returns() calls) is an object with the method:

.clear()

Removes the stub from the server

Mock

A Mock (returned by .mock().returns() calls) is an object with the methods:

.clear()

Removes the mock from the server

.called()

Returns true when at least one request has been handled by the server matching this mock

.calledOnce()

Returns true when one and only one request has been handled by the server matching this mock

.getCallCount()

Returns number the number of request handled by the server matching this mock

Request

It's an object with these fields:

  • method: string http method ('GET', 'POST', 'PUT'...)
  • urlPath: string the url path, for example '/about'
  • urlParams: Object a key-value object with url params
  • formFields: Object a key-value object with form fields
  • headers: Object a key-value object with request headers

Response

It's an object with these fields:

  • content: string http response content
  • headers: Object a key-value object with request headers
  • statusCode: number http status code (200, 404, 302...)

text(content, [headers])

Creates a response with content type 'text/plain' and with the given content and optional headers

Parameters

  • content: string
  • headers?: headers

Returns Response

html(content, [headers])

Creates a response with content type 'text/html' and with the given content and optional headers

Parameters

  • content: string
  • headers?: headers

Returns Response

json(data, [headers])

Creates a response with content type 'application/json' and with the given data and optional headers

Parameters

  • data: mixed this data is json-encoded into response's content
  • headers?: headers

Returns Response