mercredi 4 septembre 2019

Proper way to refactor functions that use functions within the same file for testing

In our application we need to use different endpoints depending upon whether the current user is authenticated. The status of authentication is stored in Redux state. This is a common pattern I have with redux selectors:

// selectors.js

import {selectIsAuthenticated} from './otherSelectors.js'

export const selectEndpoint = state => selectIsAuthenticated(state) ? 'guest' : 'authenticated'

export const selectEndpointA = state => `/rest/${selectEndpoint(state)}/a`

export const selectEndpointB = state => `/rest/${selectEndpoint(state)}/b`

When testing, this becomes complicated because i cannot mock selectEndpoint.. so then the test for selectEndpointA becomes dependent upon the implementation of selectEndpoint, which is not ideal.

What is the proper way to test something like this OR refactor it to be more easily testable?

I have considered refactoring so that selectEndpoint is passed in as an argument (or curried) for selectEndpointA such as:

export const selectEndpointA = selectEndpoint => state => `/rest/${selectEndpoint(state)}/a`

but this seems overly complicated as now in my code I would need an addition import anywhere that I wanted to use selectEndpointA

Aucun commentaire:

Enregistrer un commentaire