Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I've been quite happy setting up automated testing with mocha+chai+request so far, but I'm having trouble mocking the third party API to test the route (of my API) that calls it. I've tried using nock, but it doesn't work for my use case.

To run my tests, I start my API (npm start), and in another tab, I start the test suite (npm test). The test suite uses request to test the API over HTTP. Hence I think nock doesn't work here because it is mocking http in the 'test suite' process and not in the 'API' process.

I absolutely need to mock this third party call for 2 reasons: 1. I want to be able to run my test suite offline with everything running on my laptop 2. Since the third party API uses Oauth, hard coding credentials in the test suite (even for a test account) doesn't seem too easy.

I would really love not to leave this giant hole in my test coverage, so any advice would be much apreciated!

like image 538
saintmac Avatar asked Oct 22 '22 00:10

saintmac


1 Answers

so this is how I solve my own problem. I came up with it on my own while setting up proper testing for an app for the first time so feel free to suggest improvements. Disclaimer: I use coffee script

The first step was to launch my app from another file, starter.coffee, that essentially looks like this:

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

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

The google_mock.coffee file mocks the Google API before the app is launched from the app.coffee file. For that I use the nock! package.

The google_mock.coffee files looks like this:

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

with a lot more lines for mocking other Google api calls.

like image 149
saintmac Avatar answered Oct 24 '22 05:10

saintmac