【问题标题】:How to test a vue method with mocha Chai如何用 mocha Chai 测试一个 vue 方法
【发布时间】:2019-11-03 17:25:45
【问题描述】:

这是 MOCHA CHAI 单元测试:users.spec.js:

import { expect } from "chai";
import { shallowMount } from "@vue/test-utils";
import Users from "@/components/Users.vue";

const wrapper = shallowMount(Users);

describe("Users test", () => {
  it("Displays nice hello message", () => {
    expect(wrapper.vm.$data.msg).to.equal("Welcome to Crypto Info");
  });
  it("users model is an array", () => {
    expect(wrapper.vm.$data.users).to.be.an("array");
  });
  it("getUsers() to be a function", () => {
    expect(wrapper.vm.$methods.getUsers()).to.be.a("function");
  });
});

我找不到第三个测试的正确语法。我已经尝试了很多东西。 $methods.getUsers() 不起作用。

  1) Users test
   getUsers() to be a function:
 TypeError: Cannot read property 'getUsers' of undefined
  at Context.it (dist\js\webpack:\tests\unit\users.spec.js:15:1)

你能帮帮我吗? 谢谢。

【问题讨论】:

  • 测试方法是否存在似乎不是一个有用的测试。更有效的测试是验证方法调用的结果。

标签: vue.js webpack mocha.js chai


【解决方案1】:

该方法将简单地定义为wrapper.vm 的属性,因此您可以通过以下方式验证该方法是否存在:

expect(wrapper.vm.getUsers).to.be.a("function")

【讨论】:

  • 非常感谢,我今天试试这个!
【解决方案2】:

你可以做类似的事情

const result = typeOf wrapper.vm.$methods.getUsers();

那么测试结果是一个值为“function”的字符串?

expect(result).to.equal("function");

这对你有用吗?

【讨论】:

  • 谢谢,我今天也试试这个,让你知道!
猜你喜欢
  • 1970-01-01
  • 2017-06-20
  • 1970-01-01
  • 2020-12-07
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
相关资源
最近更新 更多