Catching Property Validation in Vue with Jest

I ran into an interesting problem. I encountered a having to test a component that didn’t have a required property set. This then throws an error and it’s not obvious as to how to test this.

1
2
3
4
5
6
7
console.error node_modules/jest-mock/build/index.js:711
[Vue warn]: Missing required prop: "tasks"

found in

---> <Anonymous>
<Root>

After some searches, I’ve found that there really is only one effective way to test this if Vue will throw an error. Arguably though, we would only be testing that Vue is doing what you tell it to be doing (not testing that we wrote a requirement on the property).

1
2
3
4
5
6
7
8
9
10
it('requires tasks', () => {
const spy = jest.spyOn(global.console, 'error');
const store = createStore({ actions, getters });
createWrapper({ store, localVue });
expect(spy).toBeCalledWith(
expect.stringMatching(/^\[Vue warn\]\: Missing required prop\: \"tasks/)
);

spy.mockReset();
});

But if you follow This Resource, it’s possilbe to instead, test that there is a ‘required’ attribute test on the props object. So now, instead of testing if Vue works, it will be testing that the code has the required feature! Much better than checking for errors.

Resources

  1. https://alexjover.com/blog/test-properties-and-custom-events-in-vue-js-components-with-jest/
  2. https://stackoverflow.com/questions/41223963/jest-how-to-mock-console-when-it-is-used-by-a-third-party-library
  3. https://vue-test-utils.vuejs.org/api/wrapper/props.html