【问题标题】:Unit Test passes without check Node.js单元测试通过而不检查 Node.js
【发布时间】:2017-04-12 12:22:36
【问题描述】:

我正在使用 Node.js(BDD 中的菜鸟)。在我的控制器中,我有这样的功能:

  var getUser = function(username, done) {
    console.log('prints');
    User.findOne({
      'local.username': username
    }, function (err, user) {
      console.log('doesn"t print');
      if (err) {
        return done('Oops, server error!', null);
      } else {
        return done(null, user);
      }
    });
  };

我正在使用 Mocha,并像这样描述了一个测试块:

  describe('can be created only using a web interface', function () {
    describe('The user name should:', function () {
      it("be a valid email", function () {
        assert(common.isValidEmail(fakeuser.local.username));
      });
      it("not already exist in the database", function () {
        userController.getUser(fakeuser.local.username, function (err, user) {
          log.info('The user name is', user);
          //I would like to assert here. But user is always undefined.
        }());
      });
    });
  });

似乎 User.findOne 没有按我预期的方式工作,因为无论如何测试都通过了,而且里面的代码甚至没有被执行。我错过了什么?

注意:在代码的其他部分调用相同的函数就可以了。

编辑

该项目可在此处访问:https://github.com/attosol/nodeseed

文档(和项目)远未完成。只需执行 npm install,然后 npm start 然后启动 MongoDB(它将使用 DB - nodeseed)。只需使用任何有效的电子邮件注册并在您的日志文件中找到激活 URL。

【问题讨论】:

  • 是否导出获取用户功能?你可以发布用户控制器吗?
  • 你没有调用done,测试不应该通过,它应该超时。
  • it('test', function(done) { done(); }) 将通过测试。如果您的测试未通过,您还应该使用assert 来抛出断言并防止done 被调用。
  • 我建议您在使用 Mocha 和文档来实际测试您的代码之前多玩一些。
  • @richardpringle 再次感谢您的指点。它有帮助。我的数据库连接出现问题,根据您的建议,我的测试开始超时。

标签: javascript node.js mocha.js bdd


【解决方案1】:

你必须写一些东西来比较

it("not already exist in the database", function(done){
    var wasCalled = false;
    userController.getUser('my@email.com', function(err, user){
      console.log('doesn"t print');
      wasCalled = true;
    });
   expect(wasCalled).toBe(true);
  });

【讨论】:

  • 试过了。 wasCalled 仍然是正确的。感谢您的帮助。
  • 另外,我想使用回调函数验证用户的一些值。我不确定为什么它根本不调用它。它也没有显示任何错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
相关资源
最近更新 更多