Last active
June 22, 2018 17:53
-
-
Save alizbazar/b0730499d8c5c36b2c26bcd986b807c8 to your computer and use it in GitHub Desktop.
Mock request-promise for Jest by first recording real API requests and then reusing them in tests offline.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
/** | |
* Makes it easy to record real API requests and save | |
* them as mocks, which can then be reused. | |
* | |
* Usage inside Jest test file: | |
* - first create a folder request-promise-mocks adjacent | |
* to this file (request-promise.js) | |
* - turn the flag on in a test to use real API: | |
* | |
* const rp = require('request-promise') | |
* rp.useMock = false | |
* | |
* - remove the flag code once you're done | |
*/ | |
const _ = require('lodash') | |
const crypto = require('crypto') | |
const fs = require('fs') | |
const { promisify } = require('util') | |
const realRequire = require.requireActual('request-promise') | |
const readFile = promisify(fs.readFile) | |
const writeFile = promisify(fs.writeFile) | |
function request (options) { | |
const optionsString = JSON.stringify(options, null, 2) | |
const name = crypto.createHash('md5').update(optionsString).digest('hex') | |
const mockFilePath = `${__dirname}/request-promise-mocks/${name}.json` | |
if (!request.useMock) { | |
return realRequire(options).then(response => { | |
const responseJSON = JSON.stringify(response, null, 2) | |
console.log(`---- REQUEST: | |
${optionsString} | |
---- RESPONSE: | |
${responseJSON} | |
-------------- | |
`) | |
return writeFile(mockFilePath, responseJSON) | |
.then(() => response) | |
}) | |
} | |
return readFile(mockFilePath, 'utf8') | |
.then(mockResponse => JSON.parse(mockResponse)) | |
.catch(err => { | |
console.error('Mock for request could not be loaded', optionsString) | |
throw err | |
}) | |
} | |
request.useMock = true | |
module.exports = request |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment