首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用chai-http测试时,服务器未执行异步功能

使用chai-http测试时,服务器未执行异步功能
EN

Stack Overflow用户
提问于 2018-07-18 12:13:51
回答 1查看 216关注 0票数 1

我的app.js中有以下函数

代码语言:javascript
复制
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是一个异步函数,其中数据是从数据库填充的

代码语言:javascript
复制
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在测试运行后执行,导致出现错误

代码语言:javascript
复制
let res = await chai.request(server).post(url).send(testObject)

输出为400错误,之后初始化memoryCache。

我该如何纠正这个问题呢?

整个测试:

代码语言:javascript
复制
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()

代码语言:javascript
复制
 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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
   }
  });
})
})

输出:

代码语言:javascript
复制
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>
EN

回答 1

Stack Overflow用户

发布于 2018-07-18 12:55:40

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51393485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档