Node.js MongoDB驱动程序文档中的断言模块



这是mongoDB驱动程序文档中的一个例子。我一直在试图弄清楚 assert.equal 在示例中的作用,但 Node.js 网站上的官方文档对我没有太大帮助——官方文档说"用相等比较运算符 (== ) 测试浅层强制相等"。所以我首先怀疑它会根据相等的真值返回真或假。但似乎没有。

我确实看过这篇文章:在nodejs中断言模块使用?。它确实有帮助 - 但还不够。我仍然不太明白"单元测试"是如何完成的。任何帮助将不胜感激,但坚实的例子将非常有帮助!

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');
  // Set up the connection to the local db
  var mongoclient = new MongoClient(new Server("localhost", 27017), {native_parser: true});
  // Open the connection to the server
  mongoclient.open(function(err, mongoclient) {
    // Get the first db and do an update document on it
    var db = mongoclient.db("integration_tests");
    db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
      assert.equal(null, err);
      assert.equal(1, result);
      // Get another db and do an update document on it
      var db2 = mongoclient.db("integration_tests2");
      db2.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
        assert.equal(null, err);
        assert.equal(1, result);
        // Close the connection
        mongoclient.close();
      });
    });
  });

断言用于执行简单的测试,以将预期结果与实际结果进行比较。如果实际结果与预期结果不匹配,则会引发异常。此功能仅用于开发目的。

它将停止执行。我运行了一个简单的节点js服务器,其中包含一个断言(assert.equal(3, 1);),它停止了执行,因为3不等于1。

如果参数 err 不为 null,则以下断言将引发异常:

assert.equal(null, err);

有关详细信息,请参阅以下链接:https://nodejs.org/api/assert.html

以下是上面链接中对断言的描述:

断言模块提供了一组简单的断言测试,可以 用于测试不变量。该模块供内部使用 Node.js,但可以通过require('assert')在应用程序代码中使用。 但是,断言不是一个测试框架,也不打算 用作通用断言库。

最新更新