Created
April 25, 2020 14:29
-
-
Save metaskills/0f2ebfe6f6b8f4e73b596864716e1d7c to your computer and use it in GitHub Desktop.
Using Jest SAM Local Environment
This file contains hidden or 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
const { spawn } = require('child_process'); | |
const NodeEnvironment = require('jest-environment-node'); | |
const { timeout, TimeoutError } = require('promise-timeout'); | |
class SamlocalEnvironment extends NodeEnvironment { | |
constructor(config) { | |
super(config); | |
} | |
async setup() { | |
await super.setup(); | |
await this.setupSam(); | |
this.global.samlocal = true; | |
} | |
async teardown() { | |
this.global.samlocal = undefined; | |
await this.teardownSam(); | |
await super.teardown(); | |
} | |
runScript(script) { | |
return super.runScript(script); | |
} | |
// private | |
async setupSam() { | |
this.server = await this.spawnSamPromise(); | |
} | |
async teardownSam() { | |
if (this.server) { this.server.kill('SIGINT'); } | |
} | |
spawnSamPromise() { | |
return timeout(new Promise((resolve, reject) => { | |
let debug = false; // Change if you want logs. Good when you update SAM. | |
let env = Object.create(process.env); | |
env['DEBUG'] = '0'; | |
env['STAGE'] = 'test'; | |
env['NODE_ENV'] = 'test'; | |
env['AWS_PROFILE'] = undefined; | |
let args = [ | |
'local', | |
'start-api', | |
'--port', | |
'3022', | |
'--template', | |
'./template.yaml', | |
'--log-file', | |
'./log/test.log', | |
'--env-vars', | |
'./.env.test.json', | |
'--docker-volume-basedir', | |
process.env.DIDPWD | |
]; | |
let server = spawn('sam', args, { env: env, cwd: '.' } ); | |
server.stdout.on('data', (data) => { | |
let msg = data.toString(); | |
if (debug) { console.log('stdout', msg); } | |
}); | |
server.stderr.on('data', (data) => { | |
let msg = data.toString(); | |
if (debug) { console.log('stderr', msg); } | |
if (/Running on/.test(msg)) { return resolve(server); } | |
}); | |
}), 10000) | |
.then((server) => { return server; }) | |
.catch((err) => { return; }); | |
} | |
} | |
module.exports = SamlocalEnvironment; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment