我想知道如何在以下代码中对视图进行单元测试:
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
,但我不确定如何使用秘银做到这一点。
答案 0 :(得分:4)
您可以将视图模型数据结构设置为所需的状态:
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
});
});