Create a mocked http server for your webapp tests and development
If you use npm:
npm install --save-dev server-mocker
If you use yarn:
yarn add --dev server-mocker
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');
});
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());
Creates an http(s) server instance where you can mock/stub responses
Parameters
options
: Objectport
: number the server will run in this portssl
?: Object you can pase an object with ssl options to use https. When not specified, the server will use httponResponseNotFound
?: (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({port: 5000});
with ssl:
const mockingServer = createServer({
port: 5000,
ssl: {
key: fs.readFileSync(__dirname + '/server.key'),
cert: fs.readFileSync(__dirname + '/server.crt'),
},
});
Configures a stubbed response for the requests that match the given predicate
Parameters
predicate
: (r:Request
) =>boolean
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'));
Similar to .stub
, the difference is you can make expectations for received requests
Parameters
predicate
: (r:Request
) =>boolean
Returns: Object
with key:
Example
const mock = mockingServer.mock(witUrlParams({message: 'ping'})).returns(text('pong'));
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()));
});
Removes all the stubs and mocks from the server.
Example
mockingServer.clearAll();
Removes all the stubs and mocks from the server and closes the server connection.
Example
mockingServer.close();
A Stub (returned by .stub().returns()
calls) is an object with the method:
Removes the stub from the server
A Mock (returned by .mock().returns()
calls) is an object with the methods:
Removes the mock from the server
Returns true
when at least one request has been handled by the server matching this mock
Returns true
when one and only one request has been handled by the server matching this mock
Returns number
the number of request handled by the server matching this mock
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 paramsformFields
: Object a key-value object with form fieldsheaders
: Object a key-value object with request headers
It's an object with these fields:
content
: string http response contentheaders
: Object a key-value object with request headersstatusCode
: number http status code (200
,404
,302
...)
Creates a response with content type 'text/plain'
and with the given content
and optional headers
Parameters
content
: stringheaders
?: headers
Returns Response
Creates a response with content type 'text/html'
and with the given content
and optional headers
Parameters
content
: stringheaders
?: headers
Returns Response
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 contentheaders
?: headers
Returns Response