Skip to content
Advertisement

How do I access localStorage or mock localStorage for Jest + vue-test-utils tests?

I am trying to test an axios request, and I need to use an auth token in order to access the endpoint, however my test fails because I am getting “Bearer null” and inputting this into my headers.Authorization. Here is my actual code below

File I’m testing:

JavaScript

Test file:

JavaScript

How do I mock or get the actual auth token in to work in my test?

Advertisement

Answer

You can try to mock localStorage before creating instance of a wrapper like this:

JavaScript

You can also spy on localStorage functions to check what arguments they were called with:

JavaScript

OR

You can delete localVue.use(axios) to let your $axios mock work correctly.

This

JavaScript

is not working because of that

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement