简体   繁体   English

使用 Mocha 和 Chai GET 进行异步测试不适用于 Node.js Rest API

[英]Asynchronous test with Mocha and Chai GET doesn't work for Node.js Rest API

Thanks in advance for reading!提前感谢您的阅读!

I'm struggling with testing even after looking for examples and tutorials, my tests are not working but I'm not sure if the issue is Chai related or my API server.即使在寻找示例和教程之后,我仍在努力进行测试,我的测试无法正常工作,但我不确定问题是与 Chai 相关还是我的 API 服务器。

All the code is open source and available here .所有代码都是开源的,可在此处获得。

I have an endpoint who should return all exercises as a list: GET /v1/exercises我有一个端点,应该将所有练习作为列表返回:GET /v1/exercises

Here is my test:这是我的测试:

 'use strict' const chai = require('chai') const chaiHttp = require('chai-http') chai.should() const app = require('../src/app') chai.use(chaiHttp) const expect = require('chai').expect describe('Exercise', () => { it('Should get all exercises', (done) => { chai.request(app).get('/v1/exercises').end((err, res) => { const result = res.statusCode expect(result).to.equal(200) done() }) }) })

And I get this error:我得到这个错误:

Error: Timeout of 2000ms exceeded.错误:超过 2000 毫秒的超时。 For async tests and hooks, ensure "done()" is called;对于异步测试和钩子,确保调用了“done()”; if returning a Promise, ensure it resolves.如果返回 Promise,请确保它已解决。 (/Users/kevintassi/Documents/project/fitigai/api/test/01.exercise.spec.js) (/Users/kevintassi/Documents/project/fitigai/api/test/01.exercise.spec.js)

You can see files here:您可以在此处查看文件:

Do you know why this issue occurs?你知道为什么会出现这个问题吗? Note that I don't have this error is the endpoint is wrong, so the timeout is appear only when the function is processing I guess.请注意,我没有这个错误是端点错误,所以我猜只有在 function 正在处理时才会出现超时。 But still don't get why.但仍然不明白为什么。

I thank you a lot in advance for your time.非常感谢您抽出宝贵的时间。 Feel free to ask me more details if needed.如果需要,请随时问我更多细节。

Issue wasn't related to Chai or Mocha.问题与 Chai 或 Mocha 无关。

It was the way how my app and server were config.这就是我的应用程序和服务器的配置方式。 Just moving the DB connection to app instead of server solve the issue since mocha make the listen to the app automatically, it know include the DB connection.只需将数据库连接移动到应用程序而不是服务器即可解决问题,因为 mocha 会自动监听应用程序,它知道包含数据库连接。

This was causing the timeout issue.这导致了超时问题。

Thank @Shaharyar for the help (in comment)感谢@Shaharyar 的帮助(在评论中)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM