Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Last active Dec 11, 2020
Embed
What would you like to do?
Helper utility to persist values between test files
/* Base Ava test config */
module.exports = {
tap: false,
verbose: true,
cache: true,
failFast: true,
failWithoutAssertions: false,
}
const baseTestConfig = require('./tests/_config.js')
module.exports = {
...baseTestConfig,
serial: true,
timeout: '30s',
concurrency: 1,
files: ['tests/lol/**/*.test.js'],
require: ['./tests/lol/setup.js'],
"environmentVariables": {
"MY_ENVIRONMENT_VARIABLE": "some value"
},
}
/* Helper utility to persist values between test files */
const fs = require('fs')
const path = require('path')
const { promisify } = require('util')
const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
const fileExists = (s) => new Promise(r => fs.access(s, fs.F_OK, e => r(!e)))
const TEMP_CACHE_FILE = path.join(__dirname, '.cache')
async function save(newData) {
const existingContents = await get()
const data = { ...existingContents, ...newData }
await writeFile(TEMP_CACHE_FILE, JSON.stringify(data))
return data
}
async function get(key) {
let contents = '{}'
if (await fileExists(TEMP_CACHE_FILE)) {
contents = await readFile(TEMP_CACHE_FILE, 'utf-8')
}
const data = JSON.parse(contents)
if (!key) return data
return dotProp(data, key)
}
// via https://github.com/developit/dlv
function dotProp(obj, key, def, p, undef) { // eslint-disable-line
key = key.split ? key.split('.') : key
for (p = 0; p < key.length; p++) {
obj = obj ? obj[key[p]] : undef
}
return obj === undef ? def : obj
}
module.exports = {
save,
get
}
const test = require('ava')
const { save } = require('../utils/persist')
test.serial('test one', async (t) => {
// persist values for next run
await save({ name: 'persist this' })
t.is(true, true)
})
const test = require('ava')
const { get } = require('../utils/persist')
test.serial('test two', async (t) => {
// Get all values
const data = await get()
console.log('All persisted data', data)
// Get value by key
const name = await get('name')
console.log('Only name value', name)
t.is(true, true)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment