Node.js: How to test my API by mocking a third-party API called my API

I am developing a RESTful Node.js API (express + mongoose) This API calls a third-party Oauth API (google, facebook, whatever).

I am very pleased with the setup of automatic testing with the request mocha + chai + so far, but I had problems mocking a third-party API to check the route (my API) that calls it. I tried using nock but this does not work for my use.

To run my tests, I launch my API ( npm start), and on another tab I launch a test package ( npm test). The test case uses a request to test the API through HTTP. Therefore, I think that knocking doesn’t work here, because it mocks http in the "test suite" process, not in the "API" process.

I absolutely need to make fun of this third party for two reasons: 1. I want to be able to run my test suite offline with everything that works on my laptop 2. Since the third-party API uses Oauth, there are strict coding requirements in the test suite (even for test account) do not seem too light.

I would really like not to leave this giant hole in my test coverage, so any advice would be greatly appreciated!

+4
source share
1 answer

this is how i solve my own problem. I came up with this myself, creating the proper testing for the application for the first time, so feel free to suggest improvements. Disclaimer: I am using a coffee script

The first step was to launch the application from another starter.coffee file, which looks something like this:

# This file starts the API locally
require './test/mocks/google_mock'
require './app'

So, to start my server for tests, instead of running coffee app.coffeeI would do coffee starter.coffee.

The file google_mock.coffeemakes fun of the Google APIs before the application runs from the file app.coffee. For this I use nock ! package.

Files google_mock.coffeeare as follows:

nock = require 'nock'
# mocking up google api
googleapis = nock('https://www.googleapis.com')
  .get('/userinfo/v2/me')
  .reply(401)

Google api.

+2

Source: https://habr.com/ru/post/1502695/


All Articles