0

My setup file runs at first before all tests. After the setup is finished, the system moves on to other tests(using axios in api tests). I m setting response.token to LoginState.authUber(in state.ts). But main problem is here into to axios.ts file, I add console.log and LoginState.authUber returns empty object in axios.ts file.

I tested whether LoginState.authUber is written correctly in my setup.ts file and confirmed that it is written correctly in the console in the setup.ts file. I just can't call it in the axios.ts file. I don't understand if I have to wait for something..How can I solve?

this is setup.ts file

setup('authenticate as uber user', async ({ page }) => {
  await page.goto(`${configEnv.baseURL}`)
  await page.locator(LoginRep.emailTextField!).fill(process.env.EMAIL!)
  await page.locator(LoginRep.passwordTextField!).fill(process.env.PASS!)
  await page.locator(LoginPageRep.loginButton!).click()
  page.on('requestfinished', async (request) => {
    if (request.url().match(/authenticate/)) {
      let response = await request.postDataJSON();
      LoginState.authUber = response.token
    }
  })
  await page.waitForSelector("#nav-channels")
  await page.context().storageState({ path: configAuth.AdminAuth });
});

This is my state.ts;

export const LoginState = {
    authUber:{} as string,
} 

This is my axios ts file;

import axios from "axios";
import { configEnv } from "../config/config"
import { LoginState } from "playwright/tests/login/login.state";

const customAxios = axios.create({
  baseURL: configEnv.apiBaseURL,
});

customAxios.interceptors.request.use(
  async (config) => {
    if (config.headers) {
      console.log('LoginState.authUber', LoginState.authUber)
      config.headers['Authorization'] = `Bearer ${LoginState.authUber}`;
      return config;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

export default customAxios
YusufOzt
  • 27
  • 8
  • `page.on`'s callback is in a different promise chain. Either promisify it or use [`waitForResponse`](https://playwright.dev/docs/api/class-page#page-wait-for-response) – ggorlen Mar 16 '23 at 17:49
  • Could you give me a sample code @ggorlen did not understood properly – YusufOzt Mar 16 '23 at 18:06
  • Does `const request = await page.waitForRequest(request => request.url().match(/authenticate/)); LoginState.authUber = request.postDataJSON().token` work for you instead of `page.on`? – ggorlen Mar 16 '23 at 18:33

0 Answers0