Meteor.collection.insert()接受callback
作为参数。例如,可以创建一个全新的Meteor项目,并在浏览器的控制台中运行以下代码。
my_collection = new Meteor.Collection("myCollection");
my_collection.insert(
{some: "object"},
function() {
console.log("finished insertion");
})
当我使用相同的代码并将其放入Laika测试时,callback
参数永远不会被调用。这是我的测试代码:
suite('testing Laika out', function() {
test('inserting into collection', function(done, server, client) {
client.eval(function() {
my_collection = new Meteor.Collection("myCollection");
my_collection.insert(
{some: "object"},
function() {
console.log("finished insertion");
done();
})
})
})
})
任何人都知道为什么在这个Laika测试中没有调用回调函数?这似乎不仅仅是Meteor.collection.insert()
的问题。
(我正在运行Ubuntu 13.04,Meteor 0.7.0.1,Laika 0.3.1,PhantomJS 1.9.2-6)
答案 0 :(得分:0)
好吧,jonS90先生,如果你用 --verbose
标志来运行Laika,你会发现异常被抛出:
[client log] Exception in delivering result of invoking '/myCollection/insert': ReferenceError: Can't find variable: done
您看,在该上下文中您无权访问done()
。以下是修改代码的方法:
test('inserting into collection', function(done, server, client) {
client.eval(function() {
my_collection = new Meteor.Collection("myCollection");
finishedInsertion = function () {
console.log("finished insertion");
emit('done')
}
my_collection.insert(
{some: "object"},
finishedInsertion)
})
client.once('done', function() {
done();
})
})
答案 1 :(得分:0)
问题是,当您在插入回调中调用done();
时,它在该函数范围内不存在。您实际上需要监听插入my_collection
并发出一个信号,该信号由客户端或服务器(在您的情况下为客户端)拾取。此外,您显然不会在测试中初始化您的收藏;应该在您的生产代码中完成。
请改为尝试:
var assert = require("assert");
suite('testing Laika out', function() {
test('inserting into collection', function(done, server, client) {
client.eval(function() {
addedNew = function(newItem) {
console.log("finished insertion");
emit("done", newItem)
};
my_collection = new Meteor.Collection("myCollection");
my_collection.find().observe({
added: addedNew
});
my_collection.insert(
{some: "object"}
)
}).once("done", function(item) {
assert.equal(item.some, "object");
done();
});
});
})
查看https://github.com/arunoda/hello-laika了解测试的基本示例。