Vue-test-utils: Required Properties Should Throw An Exception When Component Is Initialised Without Them

Created on 12 Jun 2018  路  3Comments  路  Source: vuejs/vue-test-utils

What problem does this feature solve?

Currently it is impossible to unit test correct initialisation of our components.Testing positive cases such as "does a property exist" after init works well, however with a large library of components we also need to consider negative test cases such as "don't allow component to initialise if required properties are missing" An example is shown below:

describe('Input', () => {
  it('fail initialization with no value', () => {
    const vm = mount(Input, {
      propsData: {},
    });

    // expecting above to fail due to required prop 'value'
  });
});

Currently Vue will report to the console with a warning but really this needs to be caught automatically with larger projects as manually testing and checking coverage simply by using the console is inadequate.

The ability to even configure this at a project level would be useful e.g. throwOnMissingRequiredProps: true

What does the proposed API look like?

For backwards compatibility introduce a runtime variable which would consider whether to throw or report missing required component properties to the console.

feature request

Most helpful comment

I usually handle this situation with a Spy

test('component prop is required', () => {
    const spy = jest.spyOn(global.console, 'error').mockImplementation(() => {});
    shallowMount(MyComponent);
    expect(spy).toBeCalled();
    expect(spy.mock.calls[0][0]).toContain('[Vue warn]: Missing required prop');
    spy.mockRestore();
  });

All 3 comments

I've looked into a similar feature request鈥攈asValidProps https://github.com/vuejs/vue-test-utils/issues/163.

To add support for that we would need to duplicated the props validation logic in Vue.

I suppose for this feature we could parse the warnings thrown? But I' think that approach could be brittle. We could add a throwOnWarning log instead, although I imagine that wouldn't be useful.

I understand duplicating would lead to long term maintenance issues, another suggestion: is there no way to lean on core vue development team to expose this validation logic in a more modular way? That way vue-test-utils could simply make use of the same validation logic without the maintenance overhead?

I usually handle this situation with a Spy

test('component prop is required', () => {
    const spy = jest.spyOn(global.console, 'error').mockImplementation(() => {});
    shallowMount(MyComponent);
    expect(spy).toBeCalled();
    expect(spy.mock.calls[0][0]).toContain('[Vue warn]: Missing required prop');
    spy.mockRestore();
  });
Was this page helpful?
0 / 5 - 0 ratings