我的app.js中具有以下功能
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;
memorycache.init
是一个异步函数,其中从数据库填充数据
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;
}
}
当我尝试进行chai-http测试时,在测试运行后执行memorycache.init
会导致错误
let res = await chai.request(server).post(url).send(testObject)
输出是一个400错误,之后初始化memoryCache。
我该如何纠正?
整个测试:
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'),()=> { 让url ='/ v1 / job' 让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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
}
});
})
})
输出:
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>
答案 0 :(得分:1)
您是在Mocha生命周期挂钩中列出的代码,例如before()
或beforeEach()
,还是在单个测试中?如果是在全局范围内,Node可能正在尝试并行执行memoryCache.init()
的Mocha测试,这将导致您的应用由于未正确初始化而失败。