Basic Notions
Expect: Used to construct assertions, compare a value with the expected result on a test. Chai Assertions.
Spy: A test spy is an object that records its interaction with other objects and can be used to check if a certain function was called, the arguments passed to it (if any) and what the return value is (once again, if any). Sinon Spies.
Stub: Change how the function is called on the tests. It replaces a function’s behavior, avoiding the original function invocation. Can be used to test how our unit behaves to different return values from a dependency function. Sinon Stubs.
Mount: When mounting a component, an instance is created. The component is rendered as well as its child components.
Shallow: Very similar to mount but child components are stubbed, not rendered or instanced. Very useful in order to reduce the dependencies of a component’s test.
Testing Methodologies
Vue components’ attributes are all functions.
We can approach Vue unit testing in two major ways:
Instance oriented: The component’s instance is created. Big need to control the context as there are some behaviors set by Vue (for example, lifecycle hooks being run).
Object oriented: The component’s instance is not created. The context is easier to control as every test unit (a function for example) is tested as an isolated piece of code and doesn’t require such a higher amount of mocking and stubs.
Store Tests
The store has three main structures that should be tested. Each can focus on a question that the test should answer to:
Actions: What mutations are called from the action and what’s the payload? (the testAction function will be used for this purpose: https://vuex.vuejs.org/en/testing.html)
Mutations: Was the state changed the way it was expected to?
Getters: Is the getter retrieving the data correctly?
Some tips can also be found on vue-test-utils documentation.
Testing Actions
In simple scenarios, action tests can only check the mutation payload without worrying about the current state or other dependencies like an API call:
1 | // the action |
Actions can also do API requests that, when completed, should commit a mutation with the data received. Since the test should be as independent as possible, the API call should be mocked using a stub that should resolve or reject the Promise.
1 | [actionTypes.ACTION_SET_FAV_ELEM] (context) { |
Testing Mutations
1 | // the mutation |
Testing Getters
1 | // the getter |