模拟 Vue 生命周期方法

Mocking Vue lifecycle methods

我正在为我的 vue 应用程序编写单元测试,但由于在 beforeCreate 方法中调用 session.exists 函数而遇到问题。那么我如何模拟生命周期函数或 vue.$session.exists。我试着用 sinon 模拟它,但我没能做到?

代码:

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

错误信息是:

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

您可以在 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>