Skip to content

Beter unit test docs #9544

@robvaneck

Description

@robvaneck

What problem does this feature solve?

A better guidance through the jungle of Unit tests in Vue..

What does the proposed API look like?

no related

[x] improvement docs

Hi,

Im deep into Angular, and doing my first Vue project for few months now. Hitting Vue unit test for the first time now and I believe the docs should be improved.

I'll give an example, that was breaking my head..

export default {
  name: 'TimeButtons',
  props: ['value'],
  data() {
    return {
      selected: 'radio1',
      options: []
    };
  },
  computed: {
    model: {
      get() {
        return this.value;
      },
      set(newValue) {
        this.$emit('input', newValue);
      }
    }
  },
  methods: {
    createOptions() {
       // i'll add options here
      this.options = []
      ];
    }
  },
  created() {
    this.createOptions();
  }
};
</script>

Now, I want to test if createOptions is called on created...

So I follow the docs and write:

    const wrapper = mount(TimeButtons, {
      stubs: [
        'bFormGroup',
        'bFormRadioGroup'
      ]
    });

    wrapper.setMethods({
       createOptions: jest.fn()
    });
    
    expect(wrapper.vm.createOptions.mock.calls.length).toBe(1);

But im getting

 Expected value to be:
      1
    Received:
      0

The problem was that my Jest.fn was added later than the mount.. so the component was already created... but how should I add a jest.fn on a method before the wrapper?

I tried (but fails)

  beforeEach(() => {
    TimeButtons.methods.createOptions = jest.fn();
  });

Well.. it seems there is a property methods on mount which is not mentioned in the docs :(

https://vue-test-utils.vuejs.org/api/options.html#context

so the solutions was

  it('should call createOptions on created', () => {
    const mockMethods = {
      createOptions: jest.fn()
    };

    const wrapper = mount(TimeButtons, {
      stubs: [
        'bFormGroup',
        'bFormRadioGroup'
      ],
      methods: mockMethods
    });
    expect(mockMethods.createOptions.mock.calls.length).toBe(1);
  });
  1. These basic examples should be explained in the unit test docs.
  2. The unit test docs should mention methods on mount
  3. Overall i feel the unit test docs are lacking examples and larger explanations

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions