Cha*_*nny 6 javascript assert module mongodb node.js
这是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();
});
});
});
Run Code Online (Sandbox Code Playgroud)
断言用于执行简单测试以将预期结果与实际结果进行比较.如果实际结果与预期结果不匹配,则抛出异常.此功能仅用于开发目的.
它会停止执行.我运行了一个包含assert(assert.equal(3, 1);)的简单节点js服务器,它停止了执行,因为3不等于1.
如果参数err不为null,则以下assert将抛出异常:
assert.equal(null, err);
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅以下链接:https: //nodejs.org/api/assert.html
以下是上述链接中断言的描述:
assert模块提供了一组简单的断言测试,可用于测试不变量.该模块供Node.js内部使用,但可以通过require('assert')在应用程序代码中使用.但是,assert不是测试框架,并不打算用作通用断言库.
| 归档时间: |
|
| 查看次数: |
5881 次 |
| 最近记录: |