我的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'),() => { let url =‘/v1/=>’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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
}
});
})
})输出:
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>发布于 2018-07-18 12:55:40
您在Mocha生命周期钩子(如before()或beforeEach() )中列出的代码是单独的测试吗?如果是在全局范围内,Node可能会尝试执行与memoryCache.init()并行的Mocha测试,这将导致您的应用程序由于未正确初始化而失败。
https://stackoverflow.com/questions/51393485
复制相似问题