【问题标题】:How can I unit test a view with a view-model dependency in Mithril?如何在 Mithril 中对具有视图模型依赖项的视图进行单元测试?
【发布时间】:2014-10-13 20:48:22
【问题描述】:

我想知道如何在以下代码中对视图进行单元测试:

require('mithril');

var practice = {};

practice.vm = {
  init: function() {
    this.modules = [
      { name: '1' },
      { name: '2' },
      { name: '3' }
    ]
  }
};

practice.controller = function() {
  practice.vm.init();
};

practice.view = function(controller) {
  return [
    m('h1'),
    practice.vm.modules.map(function(module) {
      return m('.module', [ m('.module-name', module.name) ]);
    })
  ];
};

module.exports = practice;

我目前有以下测试:

var chai = require('chai').should();
var practice = require('../../app/modules/practice.module');
var query = require('mithril-query');

describe('view', function() {
  it('shows all the modules along with their names', function() {
    // TODO: Mock view-model here somehow!
    //
    // I would like "practice.vm.modules" to return a stubbed
    // response so that I can test this behavior in isolation.

    var view = query(practice.view({}));

    view.find('.module').length.should.equal(3);
    view.find('.module .module-name')[0].children[0].should.equal('Bashing');
    view.find('.module .module-name')[1].children[0].should.equal('Smashing');
    view.find('.module .module-name')[2].children[0].should.equal('Whapping');
  });
});

感谢您的指导!在我看来,这样做的唯一方法是传入practice.vm,但我不确定如何使用秘银来做到这一点。

【问题讨论】:

    标签: javascript unit-testing mocha.js chai mithril.js


    【解决方案1】:

    您可以将视图模型数据结构设置为所需的状态:

    var chai = require('chai').should();
    var practice = require('../../app/modules/practice.module');
    var query = require('mithril-query');
    
    describe('view', function() {
      it('shows all the modules along with their names', function() {
    
        //store current state
        var vm = practice.vm
        //setup test state
        practice.vm = {modules: [
          {name: "Bashing"},
          {name: "Smashing"},
          {name: "Whapping"}
        ]};
    
        //test
        var view = query(practice.view({}));
    
        view.find('.module').length.should.equal(3);
        view.find('.module .module-name')[0].children[0].should.equal('Bashing');
        view.find('.module .module-name')[1].children[0].should.equal('Smashing');
        view.find('.module .module-name')[2].children[0].should.equal('Whapping');
    
        //teardown - restore original state
        practice.vm = vm
      });
    

    });

    【讨论】:

      猜你喜欢
      • 2013-08-20
      • 2014-05-18
      • 2017-09-03
      • 2014-05-29
      • 1970-01-01
      • 2010-11-24
      • 2017-02-25
      • 2013-05-10
      • 1970-01-01
      相关资源
      最近更新 更多