lundi 21 mars 2016

Ignoring browser-related variables while frontend testing react + redux app

I'm currently using mocha for frontend testing my react/redux app.

It seems like whenever there are browser-related variables in my functions, the test fails.

For example, one of my functions looks like this:

export const loginUserSuccess = (token, user) => {
    localStorage.setItem('token', token); // browser-related variable here
    return {
        type: LOGIN_USER_SUCCESS,
        payload: {
            token: token,
            user: user
        }
    }
}

Note my use of localStorage. This variable is obviously not available while testing, so any test that happens to trigger the loginUserSuccess action never passes. To be honest I don't need to test the localStorage logic at all -- I just want the action to return the correct thing. But even if I do something like this:

if (localStorage) localStorage.setItem('token', token);

I still get an error saying localStorage is undefined. How can I get the testing module to ignore certain variables?

Another example is when an action calls the global window. When making API calls, I have my action look at the window to see where to send its requests:

export const createUserInAuthStore = (username, password) => {

    let url = `${window.__BASE_URL__}/auth/user/` // look at the window here
    let data = { username, password }

    return request
      .post(url)
      .type('form')
      .send(data)
      .end()
      .then((response) => {
        return {
            token: response.body.token,
            username
        }
      })
      .catch((error) => Promise.reject(error))
}

Obviously mocha complains that window is undefined on line 3. But even if I fix that line to this:

let baseurl = window ? window.__BASE_URL__ : 'api.dockerhost'

mocha continues to throw an error.

TL;DR: Is there a way to ignore or replace browser-related variables when testing?

Aucun commentaire:

Enregistrer un commentaire