在VueJS 2.4中,我们可以通过这个来访问组件中的根数据 . $ root,就像在这个JSFiddle中一样:
https://jsfiddle.net/bjg2yL1u/1/
如果单击某个按钮,则可以在控制台中看到“橙色”,这是一个根数据,不属于触发它的待办事项 .
现在我在Jasmine测试中 . 此测试工作/运行/正确绿色 .
但是todo-item组件中的console.log输出'undefined' .
如何在测试中为这个 . $ root实例注入数据?
describe("TodoItem", function() {
var sut;
var message = {text:'word'}
beforeEach(function() {
var Constructor = Vue.extend(TodoItem);
sut = new Constructor({
propsData: {
todo: message,
}
}).$mount();
});
it("Should be able to reverse the given word", function() {
// Given
expect(sut.todo.text).toEqual('word');
expect($(sut.$el).find('li').text()).toEqual('word');
//When
sut.reverseMessage();
// Bang !! problem here. 'undefined' is printed, because there is nothing attached to this.$root when inside a test
// Then
expect(sut.todo.text).toEqual('drow');
});
});
1 回答
当您在此处创建扩展组件的Vue时:
Constructor
是$root
.TodoItem
组件中没有display_light
属性,这就是console.log打印undefined
的原因,因为它实际上是undefined
.如果要将该数据属性添加到组件中,以便测试按预期工作(可能是个坏主意),您可以这样做:
这是你的fiddle updated .