尝试从unit testing连接到mongo时超时

我想写一些unit testing用逗号和mongoose来validation与mongo的数据交互。

我不想在这里嘲笑mongoose,因为我特别想validationmongo文档被创build/修改/处理的方式。

package.json被configuration为使节点模块解除locking:

 { "jest": { "unmockedModulePathPatterns": [ "node_modules" ] } } 

在我的实际testing中,我build立了一个beforeAll()钩子来处理连接到mongo:

 const mongoose = require('mongoose'); describe('MyTest', () => { beforeAll((done) => { mongoose.connect('mongodb://127.0.0.1:27017/test'); let db = mongoose.connection; db.on('error', (err) => { done.fail(err); }); db.once('open', () => { done(); }); }); it('has some property', () => { // should pass but actually never gets run expect(1).toBe(1); }); }); 

这是输出:

 /usr/local/bin/node node_modules/jest-cli/bin/jest.js --verbose Using Jest CLI v0.10.0, jasmine2 FAIL src/lib/controllers/my-controller/__tests__/my-test.js (5.403s) MyTest ✕ it has some property MyTest › it has some property - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. at Timer.listOnTimeout (timers.js:92:15) 1 test failed, 0 tests passed (1 total in 1 test suite, run time 5.903s) Process finished with exit code 1 

testing每次都会超时,因为done()永远不会在beforeAll()钩子中被调用,也不会抛出任何错误,也不会打印到控制台。 我可以在beforeAll()钩子中放置断点来validation正在运行的代码。 看起来mongoose在试图打开与蒙古的连接时挂起来,然后笑话testing正在结束。

当我在jest环境之外运行类似的代码时,它按预期连接(即时)。 怀疑这可能会导致问题,我已经尝试完全禁用jest的automockfunction,但行为保持不变。

我想我已经错过了难以置信的明显的东西…任何想法可能会发生什么?

  • jest-cli诉0.10.0
  • mongoose诉4.4.11

更新:

  • 尝试用普通function(done) {}replaceES6箭头函数语法function(done) {} 。 没有不同。
  • 尝试通过传递done参数进行testingasynchronous,并在testing完成时调用它。 没有不同。
  • 尝试在声明errorconnected事件处理程序之后调用mongoose.connect()
  • 尝试注释掉所有mongoose相关的代码来检查beforeAll()钩子是否正常工作 – 这是。

Jest- Jasmine与Jasmine不同
你使用的语法实际上属于Jasmine 2.0+,而不是Jest-jasmine。 所以如果你想继续使用笑话,你必须看笑话文件find答案。
更甚者,“以前所有”都不是标准的开玩笑注入variables,见笑嘻嘻。

我用Jasmine 2.3.4运行你的代码,它运行得很好。 我试图答应/坑开玩笑,完成这项工作,但失败了。

首先, 安装茉莉花 。

 npm install -g jasmine mkdir jasmine-test cd jasmine-test jasmine init jasmine examples touch spec/mongodbspec.js 

这是我的目录结构:

 fenqideMacBook-Pro:jasmine-test fenqi$ ls -R .: spec/ ./spec: mongodbspec.js support/ ./spec/support: jasmine.json 

然后,编辑spec / mongodbspec.js,我只是在你的代码中添加一行“'strict strict';”。

 'use strict'; const mongoose = require('mongoose'); describe('MyTest', () => { beforeAll((done) => { mongoose.connect('mongodb://127.0.0.1:27017/test'); let db = mongoose.connection; db.on('error', (err) => { done.fail(err); }); db.once('open', () => { done(); }); }); it('has some property', () => { // should pass but actually never gets run expect(1).toBe(1); }); }); 

最后,运行“茉莉花”:

 fenqideMacBook-Pro:jasmine-test fenqi$ jasmine Started . 1 spec, 0 failures Finished in 0.023 seconds