0

I don´t have much experience with unit testing. What is the proper way to test a method imported from a JS file or from another component?

This is a sample component I created a localSum just to use on the test.

<template>
    <div class="fixed-center text-center text-h2">
        <p>{{ getSum }}</p>
    </div>
</template>

<script>
import { sum } from './testComponent.js';

export default {
    name: 'TestComponent',
    data() {
        return {
            a: 10,
            b: 20
        }
    },
    computed: {
        getSum() {
            return sum(this.a, this.b);
        }
    },
    methods: {
        localSum(a, b) {
            return a + b;
        }
    }
};
</script>

The JS file:

export function sum(a, b) {
    return a + b;
}

This is the test, maybe I should not be using wrapper.vm to access the method? One note: On the real component I don't want to test the method directly, which is why I did not import sum from the JS file.

import { mount } from '@vue/test-utils';
import TestComponent from '@components/TestComponent.vue';

describe('Testing component', () => { 
    test('Testing local method', () => { 
        const wrapper = mount(TestComponent);

        expect(wrapper.vm.localSum(10, 20)).toBe(30);
    });

    test('Testing method from js file', () => { 
        const wrapper = mount(TestComponent);

        expect(wrapper.vm.getSum(10, 20)).toBe(30);
    });
});

Test result:

Testing component
    ✓ Testing local method (6 ms)
    ✕ Testing method from js file (2 ms)

  ● Testing component › Testing method from js file

    TypeError: wrapper.vm.getSum is not a function

Thanks!

1 Answer 1

0

In your example getSum() is a computed property that doesn't take any argument. Therefore to test it you probably just need to do:

expect(wrapper.vm.getSum).toBe(30);

instead of:

expect(wrapper.vm.getSum(10, 20)).toBe(30);
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.