2014-10-13 8 views
2

Мне интересно, как я бы модульного тестирования мнение в следующем коде:Как я могу выполнить модульное тестирование вида с зависимостью модели представления в Mithril?

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, но я не уверен, как это сделать с помощью Мифрила.

ответ

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

});