gpt4 book ai didi

javascript - 我如何在 Mithril 中对具有 View 模型依赖项的 View 进行单元测试?

转载 作者:行者123 更新时间:2023-11-29 18:12:13 25 4
gpt4 key购买 nike

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

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 执行此操作。

最佳答案

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

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

});

关于javascript - 我如何在 Mithril 中对具有 View 模型依赖项的 View 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26348632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com