NodeJS Mock第三方服务

I have an example endpoint, when a request is submitted to it, I do another request to a third party service which turns out to be malfunctional at times. I want to simulate this service being malfunctional so my tests can be relevant. Here is some example code

it('should handle malfunctional 3rd party service', done => {
  Frisby.post(Endpoints.randomEndpoint, {
    email: 'johndoe@gmail.com',
    firstName: 'John',
    lastName: 'Doe'
  })
  .expect('status', 400)
  .expect('jsonTypes', Common.Types.ErrorModel)
  .done(done);
});

On my server side, I have something like..

app.post('randomEndpoint', (req, res) => {
  request('http://3rdpaty.com/api')
    .then(data => {
      res.send(200);
    })
    .catch(err => {
      res.send(500);
    })
})

My goal is tomock the response from the thrid pary service. Any ideas?

You can mock your http request using nock library

nock('http://3rdpaty.com/')')
 .post('/api/', {
   email: 'johndoe@gmail.com',
   firstName: 'John',
   lastName: 'Doe'
 })
 .reply(400, { id: '123ABC' });

You can run a mock server locally and request to the local mock server whenever the tests should run.

Check out json-server or mockserver documentation for instructions on how to run a mock server in node.js

Running a mock server locally (according to mockserver):

var http    =  require('http');
var mockserver  =  require('mockserver');

http.createServer(mockserver('mocks')).listen(9001);

Add a file to mocks/api directory, named GET.mock(for GET requests) or POST.mock(for POST requests) and specify the result of the API call:

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8

{
   "Accept-Language": "en-US,en;q=0.8",
   "Host": "headers.jsontest.com",
   "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
   "Accept": 
   "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}

Alter the URL of the 3rd party server whenever you are running the tests (use the port of your mock server):

app.post('randomEndpoint', (req, res) => {
  request('http://127.0.0.1:9001/api')
    .then(data => {
      res.send(200);
    })
    .catch(err => {
      res.send(500);
    })
})

A better solution for altering the URL of the 3rd party is to specify the TEST environment using env variables and get the URL using config files based on the environment your program is running on. e.g. if your program is running on Production environment then the URL must be http://3rdpaty.com/api but if your program is running on TEST environment then the URL must be http://127.0.0.1:9001/api.