Unit Testing for Vue Router Global After Hooks

William Yu
2 min readAug 24, 2022

--

Intro

It is always not easy to do the unit testing for the Vue Router. People prefer to implement end-to-end testing for this. Especially, if you have defined some Vue router global hooks, it would be more difficult to testing the execution of them.

Fortunately, we still can find a way to do the unit testing for the Vue Router Global After Hooks.

Background

In my project, I have implemented afterEach as global after hooks in my Vue router settings. The propose of it is to execute a service call after the user successful login.

The implementation of the code is like this:

The code works fine but cause some problem for unit testing. Even we can attempt to call afterEach by using router.afterHooks[0](). We will get an error about we didn't pass the correct arguments for it.

Refactoring for unit testing

To prepare for unit testing, we may need to refactor the code to make it decoupled. One solution would be independently exporting the afterEach after hook. We can make the change as below:

After the refactoring, we can do unit testing much easier.

Unit testing

For the unit testing, we can mock the service (JobService), and test if it has been called.

The test will be passed after we execute the test. Cheers!

Originally published at https://williamyuaus.com on August 24, 2022.

--

--

William Yu
William Yu

Written by William Yu

Software Developer from the user side

No responses yet