1

I'm trying to test the methods in jest framework. For javascript methods i was able to import the methods from file using require() function and test it (expect(addition(1,2).toBe(3))). But unable to replicate the same in VueJS methods.

  // VueJS
  export default defineComponent({
  name: "App",
  components: {
    HelloWorld,
  },
  methods: {
    addition(a: number, b: number) {
      return a + b;
    },
    subtraction(a: number, b: number) {
      return a - b;
    },
    multiplication(a: number, b: number) {
      return a * b;
    },
  },
});

test file

import addition from "./App.vue"
describe("HelloWorld.vue", () => {
  it("testing vue method", () => {
    expect(addition(1,2).toBe(3));
  });
});

//error on line 4 states "Value of type 'DefineComponent<{}, {}, any, ComputedOptions, MethodOptions, ComponentOptionsMixin, 
// ComponentOptionsMixin, ... 4 more ..., {}>' is not callable. Did you mean to include 'new'?"
3
  • Check out vue-test-utils.vuejs.org/guides/#knowing-what-to-test - my two cents...for the added difficulty of diagnosing failing tests in a VDOM I'd rather just run browser tests. Maybe I'm just missing the mark with Jest though. Commented Jul 5, 2021 at 18:13
  • Yes! I was referring to do unit testing using JEST framework. Commented Jul 5, 2021 at 18:15
  • 1
    The test fails because default import is component definition object, while you expect it to be addition function for some reason. It's the same with vanilla JS tests when imports go wrong. Could be expect(comp.options.methods.addition.call(mockInstance, 1, 2)).... But it's correct to test a component with Vue utils as said. A test with Jest alone doesn't have much value because you test not original behaviour but something else. Commented Jul 5, 2021 at 19:57

1 Answer 1

2

The App.vue file is compiled into a component definition, which is used to instantiate the App component with Vue Test Util's mount or shallowMount, which results in a test wrapper. The wrapper has a vm property that provides direct access to the component's methods and props.

So your test should look similar to this:

import { shallowMount } from "@vue/test-utils";
import App from "./App.vue";

describe("App.vue", () => {
  it("testing vue method", () => {
    const wrapper = shallowMount(App);
    expect(wrapper.vm.addition(1,2)).toBe(3);
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.