I am trying to use axios-mock-adapter
to mock the response I get when calling the Spotify API to request an access token. Here is the function that does just that…
export const discovery = {
authorizationEndpoint: "https://accounts.spotify.com/authorize",
tokenEndpoint: "https://accounts.spotify.com/api/token",
};
...
export const getTokenRequest = async (response: AuthSessionResult, request: AuthRequest) => {
const accessCode = response.params.code;
console.log("Successfully authorised user and obtained access code", accessCode);
await AsyncStorage.setItem("code", accessCode);
const codeVerifier = request?.codeVerifier || ""
console.log("Successfully obtained code verifier from request", codeVerifier);
await AsyncStorage.setItem("codeVerifier", codeVerifier);
const data = {
client_id: clientId,
grant_type: "authorization_code",
code: accessCode,
redirect_uri: redirectUri,
code_verifier: codeVerifier
}
try {
const tokenResponse = await axios.post(
discovery.tokenEndpoint,
qs.stringify(data),
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
})
console.log("Successfully obtained token response", tokenResponse);
storeAccessToken(tokenResponse);
storeRefreshToken(tokenResponse);
} catch(error) {
console.log("Failed to obtain token request", error)
}
}
…And here is my corresponding test…
it("obtains an access code and a refresh token from the authorization code", async () => {
const mockAxiosAdapter = new MockAdapter(axios);
const mockTokenResponse = { data: { access_token: "DEF", refresh_token: "ABC" } };
const authResult = { type: "success", params: { code: "123" } }
const authRequest = { codeVerifier: "XYZ" }
mockAxiosAdapter.onPost(AuthManager.discovery.tokenEndpoint).reply(200, mockTokenResponse);
await AuthManager.getTokenRequest(authResult as AuthSessionResult, authRequest as AuthRequest);
expect(AsyncStorage.setItem).toHaveBeenCalledWith("access_token", "DEF");
expect(AsyncStorage.setItem).toHaveBeenCalledWith("refresh_token", "ABC");
})
})
When running through this though, it does not seem that my mock post API call that I made is called, and instead, I get my tokenResponse being undefined. I debugged through it and it seems that my mock has been set up by axios-mock-adapter
…
…And when I step into my function, it seems that everything has been set up alright on that front too…
But it does not work so I have come here to hopefully get unstuck! Thank you in advance for any help/insight on this problem!
EDIT: I have now posted this on the Github issues for axios-mock-adapter
with an update . In short, I made an axios instance for my AuthManager
. Doing this made it so that the axios instance is the same for both my getTokenRequest
function and new MockAdapter(axios)
, but now it is not calling the mock and making an actual API call.
2