首页 文章

如何在测试VueJS组件时将数据设置为 . $ root?

提问于
浏览
2

在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 回答

  • 2

    当您在此处创建扩展组件的Vue时:

    var Constructor = Vue.extend(TodoItem);
    sut = new Constructor({
      propsData: {
        todo: message,
      }
    }).$mount();
    

    Constructor$root . TodoItem 组件中没有 display_light 属性,这就是console.log打印 undefined 的原因,因为它实际上是 undefined .

    如果要将该数据属性添加到组件中,以便测试按预期工作(可能是个坏主意),您可以这样做:

    var Constructor = Vue.extend(TodoItem);
    sut = new Constructor({
      propsData: {
        todo: {text: "hello world"},
      },
      data(){
        return {
          display_light: 'orange'
        }
      }
    }).$mount();
    

    这是你的fiddle updated .

相关问题