Test your VueJS + TypeScript application; part 2

Testing an action

Calling an “action” in test context is similar to calling “mutations” and “getters”. There is a slight difference, there is a need to cast the call as “ActionHandler” class from “vuex” module (because actions can have two types, one of them not being callable).

Calling an actions
Excerpt of the context object
Checking that a promise resolved
Checking that a promise
Wait for the end of your action with “await” before your expectations

Checking commit and dispatch calls

An “action” calls “commit” to call “mutations” and “dispatch” to call “actions”. Those are handled through the “context” object. So there is a need to have mocked functions; to create mock function with Jest: “jest.fn()”.

Mock function “dispatch” and “commit” to achieve your expectations
Checking the number of calls
Checking the calls

Mocking dependencies

As stated above, “actions” contain more advanced behavior than “mutations” and “getters” that we saw previously. They are calling APIs, calling complex business logic, etc. And usually, all of this comes from dependencies, whether they are internal to your code base, or third party. In any case, we need to make sure those dependencies behave as we expect them for our tests. That’s where “mocks” comes handy (if you don’t know what a mock is, take a look at the Wikipedia article).

Import the class we will mock
Import the utils from ts-jest
Create the mock
Replace the implementation with a mock for the tests
Import and mock axios
Mocking a method of a 3rd party library
Use the mocks in your expectations
The imports and mocks part
An example of a test on action
An other example of testing an action (note the async)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store