lkatz92
lkatz92

Reputation: 31

How do I test if my data changes? (Vue JS, Jest, Unit Testing)

I am working on unit testing my code with Jest in my frontend Vue JS project, and one of the tests I want to write is:

it('should show the advanced filters if user_id exists', () => {
  })

This is part of a created property in the Javascript code:

this.user_id = localStorage.getItem("user_id");
      if (this.user_id) {
        this.renderAdvancedFilters = true;
      }

Also, below is part of the data that is being exported:

export default {
  data: () => ({
    renderAdvancedFilters: false,
    user_id: localStorage.getItem("user_id"),

So, renderAdvancedFilters is originally set to false, but if a user id exists, then it is set to true, and the advanced filters are then displayed. How do I write a unit test where I am showing that if a user id exists, then advanced filters is shown on the app? Since this is a created property, there is no interaction with the app to test, so I think I should just be testing the data, but I'm not sure how to.

Should I be mocking the data of this.user_id? If so, how do I do that?

Thank you

Upvotes: 0

Views: 845

Answers (1)

T. Short
T. Short

Reputation: 3614

I think you only need to mock this localStorage.getItem();.

Mock it to return a dummy user id and then you simply run the test and check that the outcome is what you expect.

Seems like that is the only dependency you need to mock.

Something like:

global.localStorage = {
    getItem: jest.fn(() => 'some user id')
};

Upvotes: 1

Related Questions