【问题标题】:How to set data to this.$root when testing a VueJS component?测试 VueJS 组件时如何将数据设置为 this.$root?
【发布时间】:2017-08-12 13:42:43
【问题描述】:

在 VueJS 2.4 中,我们可以通过 this.$root 从组件访问根数据,就像在这个 JSFiddle 中一样:

https://jsfiddle.net/bjg2yL1u/1/

如果你点击一个按钮,你可以在控制台看到'橙色',这是一个根数据,不属于触发它的todo-item。

现在我在 Jasmine 测试中。此测试正常工作/运行/呈绿色。

但是 todo-item 组件中的 console.log 输出 'undefined'。

如何在测试中向 this.$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');

  });
});

【问题讨论】:

    标签: javascript testing jasmine vue.js vuejs2


    【解决方案1】:

    当您像这里一样从扩展组件创建 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

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 2016-01-19
      • 1970-01-01
      • 2017-08-26
      • 2017-09-25
      • 2012-07-10
      相关资源
      最近更新 更多