1

我的 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/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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
   }
  });
})
})

输出:

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>
4

1 回答 1

1

您在 Mocha 生命周期钩子(例如before()or )中列出的代码beforeEach(),还是在单个测试中列出的代码?如果它在全局范围内,Node 可能会尝试并行执行 Mocha 测试memoryCache.init(),这将导致您的应用程序由于未正确初始化而失败。

于 2018-07-18T04:55:39.817 回答