【问题标题】:Mocking Vue lifecycle methods模拟 Vue 生命周期方法
【发布时间】:2018-03-23 15:17:51
【问题描述】:

我正在为我的 vue 应用程序编写单元测试,但由于在 beforeCreate 方法中调用 session.exists 函数而出现问题。那么我如何模拟生命周期函数或 vue.$session.exists。我尝试使用 sinon 来模拟它,但我没有成功?

代码:

beforeCreate: function() {
  if (!this.$session.exists()) {
    this.$router.push('/')
  }
}

错误信息是:

TypeError: "cannot read property 'exists' of undefined"

【问题讨论】:

  • 好吧,欢迎向我们展示您尝试了什么。这样,人们就可以更轻松、更快捷地找到出路。
  • 希望它调用vue.$session.exists是吗?
  • beforeCreate: function () { if (!this.$session.exists()) { this.$router.push('/') } } 错误信息是:TypeError: "cannot read property '存在'未定义"

标签: vue.js sinon


【解决方案1】:

mount()ing 时可以模拟$session

const $session = { exists() { return true; } };
const component = mount(MyComponent, {
  mocks: {
    $session
  }
});

下面的演示。

var MyComponent = Vue.component('MyComponent', {
  template: '<div> Hello </div>',
  beforeCreate() { console.log('this.$session.exists() -->', this.$session.exists()); },
});

// specs code ///////////////////////////////////////////////////////////
var mount = vueTestUtils.mount;
describe('MyComponent', () => {
  it("mocks $session successfully", () => {
    const $session = { exists() { return true; } }
    const parent = mount(MyComponent, {
      mocks: {
        $session
      }
    });

    expect(parent.vm.$session).not.toBe(undefined);
  });
});

// load jasmine htmlReporter
(function() {
  var env = jasmine.getEnv()
  env.addReporter(new jasmine.HtmlReporter())
  env.execute()
}())
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css">
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
<script src="https://npmcdn.com/vue@2.5.16/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-template-compiler@2.5.15/browser.js"></script>
<script src="https://rawgit.com/vuejs/vue-test-utils/2b078c68293a41d68a0a98393f497d0b0031f41a/dist/vue-test-utils.iife.js"></script>

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 2019-01-18
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多