javascript - 测试VueJS组件时如何将数据设置到this.$root?

标签 javascript testing jasmine vue.js vuejs2

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

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

如果单击按钮,您可以看到控制台中显示“橙色”,这是根数据,不属于触发它的待办事项。

现在我正在进行 Jasmine 测试。该测试正常工作/运行/为绿色。

但是 todo-item 组件内的 console.log 输出“未定义”。

在测试中如何将数据注入(inject)到 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');

  });
});

最佳答案

当您像这里一样从扩展组件创建 Vue 时:

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

构造函数$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 .

关于javascript - 测试VueJS组件时如何将数据设置到this.$root?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45650979/

相关文章:

php - XFBML 和 Facebook 登录按钮

javascript - 如果总是以不同/随机名称返回,如何绑定(bind)到 json key ?

javascript - 将鼠标悬停在区域上时如何避免 CSS 闪烁?

android - 是否可以以编程方式运行 InstrumentationTestRunner?

AngularJS 错误 : Unexpected request (No more requests expected)

javascript - "new"谷歌日历中的 MutationObserver

angular - 如何为包含带 Angular 路由器的组件设置测试?

testing - 如何在本地运行 archetypes.querywidget 测试套件?

jasmine - 如何使用 Protractor 测试页面上不存在某个元素?

javascript - 将代码放在 Jasmine 测试 + Meteor 的正确目录中