【问题标题】:Mocha test.Timeout 2000ms摩卡测试。超时 2000 毫秒
【发布时间】:2018-11-13 22:43:18
【问题描述】:

我做错了什么?我正在尝试将手机保存到我的数据库,但 mocha 说超时超过 2000 毫秒。 我的手机架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const phoneSchema = new Schema({
    company: String,
    modelname: String,
    numbername: String,
    picture: String,
    price: String,
});

const Phone = mongoose.model('phone', phoneSchema);

module.exports = Phone;

还有我的测试文件:

    const mocha = require('mocha');
const assert = require('assert');
const Phone = require('../models/phone-model');


//describe tests
describe('Saving records', function(){
    //create tests
    it('Saves phone to the db',function(done){

        var phone1 = new Phone({
            company: "Samsung",
            modelname: "Galaxy",
            numbername: "S5",
            picture: "https://drop.ndtv.com/TECH/product_database/images/2252014124325AM_635_samsung_galaxy_s5.jpeg",
            price: "12500P"
        });

        phone1.save().then(function(){
            assert(phone1.isNew === false);
            done(); 
        });

    });

});

我不明白我在这里做错了什么......在此之前它总是对我有用。 错误:超过 2000 毫秒的超时。对于异步测试和钩子,确保调用了“done()”;如果返回 Promise,请确保它已解决。 (C:\Users\User\Desktop\Oauth\test\phone_test.js)

【问题讨论】:

  • 一个简单的解释是 save() 没有解析。尝试添加catch()
  • 这是从规范中返回承诺是一个好主意而使用 done 不是的少数原因之一。
  • 不要添加捕获。只需返回您的then 的承诺即可。如果它拒绝,测试将失败。不需要冗余的故障处理程序。

标签: javascript node.js mongodb testing mocha.js


【解决方案1】:

正如 cmets 所说,如果来自 save 方法的承诺得到解决,您只会调用 done,这意味着如果您的数据库发送错误响应,您的测试将超时。

由于您正在处理承诺,请尝试使用 mocha 的 built-in promise support 而不是 done 回调:

const mocha = require('mocha');
const assert = require('assert');
const Phone = require('../models/phone-model');

describe('Saving records', function(){
    // Note there is no `done` argument here
    it('Saves phone to the db',function(){

        var phone1 = new Phone({
            company: "Samsung",
            modelname: "Galaxy",
            numbername: "S5",
            picture: "https://drop.ndtv.com/TECH/product_database/images/2252014124325AM_635_samsung_galaxy_s5.jpeg",
            price: "12500P"
        });

        // Note returning the promise here...
        return phone1.save().then(function(){
            assert(phone1.isNew === false);
        });

    });

});

让我们知道您在此之后看到了什么。希望您会看到一条实际的错误消息,可以帮助您找出问题所在。您的数据库也很可能需要超过 2000 毫秒的时间来响应,尽管这种可能性更大。

【讨论】:

    猜你喜欢
    • 2017-06-23
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 2015-02-05
    相关资源
    最近更新 更多