Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Jest SAM Local Environment
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
You can’t perform that action at this time.