【问题标题】:Accessing a Meteor Template Helper Function in Jasmine for Integration Testing在 Jasmine 中访问 Meteor 模板辅助函数以进行集成测试
【发布时间】:2014-12-24 07:50:21
【问题描述】:

我正在尝试在一个流星项目上运行 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 测试访问我的模板辅助函数吗?

【问题讨论】:

    标签: javascript unit-testing templates meteor jasmine


    【解决方案1】:

    在 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);
    }
    

    【讨论】:

      【解决方案2】:

      Meteor 1.3 对此问题的更新答案(对不起,我使用 mocha,但不影响答案):

      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) 封装成一个漂亮、干净的助手。

      【讨论】:

        【解决方案3】:

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

        此外,考虑阅读或再次阅读 Llama 博士博客中与 Jasmin/Meteor 相关的著名且明确的文章:Bullet-proof Meteor applications with Velocity, Unit Testing, Integration Testing and Jasmine

        【讨论】:

        • 我已经阅读了那篇文章——我学到了很多东西,但我仍然无法让测试正常工作。您说要使客户端测试正常工作,还需要做一件事,那会是什么?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-20
        • 2013-05-12
        • 2014-07-29
        • 1970-01-01
        • 1970-01-01
        • 2013-02-14
        • 1970-01-01
        相关资源
        最近更新 更多