如何在Mithril中对具有视图模型依赖关系的视图进行单元测试

How can I unit test a view with a view-model dependency in Mithril?

本文关键字:视图 依赖 模型 关系 单元测试 Mithril      更新时间:2023-09-26

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

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,但我不确定如何使用Mithril。

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

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

});