繁体   English   中英

访问 Jasmine 中的 Meteor 模板辅助函数进行集成测试

[英]Accessing a Meteor Template Helper Function in Jasmine for Integration Testing

我正在尝试在流星项目上运行 Jasmine 客户端集成测试。 我使用的是meteor 0.9.4和用于Jasmine 的sanjo:jasmine包。

我写了一个测试,它看起来像:

describe("Template.dashboard.tasks", function() {

    it("ela displays correct assessment", function() {
        Session.set("selected_subject", "math");
        Session.set('selected_grade', "1");

        tasks = Template.dashboard.tasks();
        expect(true).toBe(true);
    });
});

在测试结束之前我收到一个错误:

Cannot read property 'tasks' of undefined

这意味着Template.dashboard在此测试范围内不存在。

Template.dashboard.tasks()是一个完全有效的辅助函数,它位于视图文件夹内的js文件中。 常规Jasmine测试按预期工作,但是一旦我尝试从另一个文件使用我自己的功能之一,它就不起作用。

我的问题是:我需要做些什么才能让Jasmine测试访问我的模板辅助函数?

在 Meteor 中,模板辅助函数过去的格式如下:

Template.dashboard.tasks = function () {
    ...
};

但这已被弃用,新格式是:

Template.dashboard.helpers({
    tasks: function(){
        ...
    }
});

在 Jasmine 中,使用以前的格式,您可以访问辅助函数,例如:

Template.dashboard.tasks();

但是现在你必须像这样调用辅助函数:

Template.dashboard.__helpers[' tasks']();

Sanjometeor-jasmine repo 的原作者)建议使用这样的函数来更容易调用辅助函数(特别是如果语法最终再次更改):

function callHelper(template, helperName, context = {}, args = []) {
    template.__helpers[` ${helperName}`].apply(context, args);
}

Meteor 1.3 这个问题的更新答案(对不起,我使用摩卡咖啡,但它不影响答案):

测试时不会急切地设置 Template.foo 和 Template.foo 助手,因此您需要导入foo.html然后foo.js

这是一个例子:

import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { Foo } from '/collections/foo.js';
import { assert } from 'meteor/practicalmeteor:chai';
import './foo.html';  // now Template.foo is defined
import './foo.js';    // now Template.foo.__helpers[' bar'] is defined


describe('foo handlers', () => {
    it("Should test bar", () => {
       // don't forget the space, helper key is ' bar' not 'bar'
       var bar = Template.foo.__helpers[' bar'].apply({foo:"bar"},3); 
       assert.Equal(bar,'bar');
    });
});

当然,如前所述,您绝对应该将奇怪的Template.foo.__helpers[' bar'].apply(context,args)封装成一个漂亮、干净的助手。

服务器部分的测试从一开始就运行良好,为了在前端部分运行测试,确实还有一件事要做。 我会尽力找到你的。

此外,请考虑阅读或再次阅读 Llama 博士博客中与 Jasmin/Meteor 相关的著名而明确的文章: 防弹 Meteor 应用程序与速度、单元测试、集成测试和 Jasmine

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM