In my app.js file, there is a function that I am using:
let memoryCache = require('./lib/memoryCache');
memoryCache.init().then(() => {
console.log("Configuration loaded on app start", JSON.stringify(memoryCache.getCache()));
});
app.use('/v1', v1);
...
module.exports = app;
The memorycache.init
function is asynchronous and retrieves data from a database.
module.exports = function () {
let cache = {};
return {
init: async () => {
console.log('called this')
cache['repairStatus'] = formatData(await getRepairStatus());
cache['actionStatus'] = formatData(await getActionStatus());
cache['problemFound'] = formatData(await getProblemFound());
cache['complaintCode'] = formatData(await getComplaintCode());
cache['productType'] = formatData(await getProductType());
console.log('cache is', cache)
},
getCache: (key) => {
if (key) return cache[key] || null;
else return cache;
}
}
However, when attempting a chai-http test, the memorycache.init
function runs after the test causing an error.
let res = await chai.request(server).post(url).send(testObject)
This results in a 400 error before the memoryCache initializes properly.
How can I resolve this issue?
Here is the entire test code:
const chai = require('chai');
const getTestJob = require('../../lib/testutils').getTestJob;
const chaiHttp = require('chai-http');
const server = require('../../../app.js');
chai.use(chaiHttp);
const expect = chai.expect;
const assert = chai.assert;
describe(('Api- CreateJob'), () => { let url = '/v1/job' let testSRJob = getTestJob()
before(async () => {
})
beforeEach(() => {
})
after(async () => {
})
describe('*** HAPPY CASES ***', () => {
it('successful test', async () => {
console.log('calling test')
let result = await chai.request(server).post(url).set('Authorization', 'auth').send(testSRJob)
if (result.status !== 200) {
console.log('Status: ', result.status)
console.log('Error: ', result.error)
assert.fail()
} else {
console.log('Yippie!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
}
});
})
})
Output:
called this
... some logging from the api tested
Error: { Error: cannot POST /v1/job (400)
status: 400,
text: '{"message":"Create job failed","code":"E1002","errData":{}}',
method: 'POST',
path: '/v1/job'
>> then failure report in the test
cache is <cache data>
Configuration loaded on app start <cache data>