Reacting
Reacting

Reputation: 6123

I am getting a timeOut error on a jest test: thrown: Exceeded timeout of 5000 ms for a test

This is the code where this is happening:

    export const initializeSpotifySDK = async (token: string, trackId: string, contextUri: string, playbackStateChangeHandler: (state) => void, errorHandler: (message: string) => void): Promise<SpotifyPlayer> => {
      embedSpotifyScript();
    
      return new Promise(resolve => {
        window.onSpotifyWebPlaybackSDKReady = () => {
          try {
            // @ts-ignore
            const player = new Spotify.Player({
              name: 'Mira',
              getOAuthToken: callback => { callback(token); }
            });
    
            // Error handling - pass an error handler!!!
            player.addListener('initialization_error', ({ message }) => {
              errorHandler(message);
            });
            player.addListener('authentication_error', ({ message }) => {
              errorHandler(message);
            });
            player.addListener('account_error', ({ message }) => {
              errorHandler(message);
            });
            player.addListener('playback_error', ({ message }) => {
              errorHandler(message);
            });
    
            // Playback state handler - pass a handler as well!!!
            player.addListener('player_state_changed', state => { playbackStateChangeHandler(state); });
    
            player.addListener('ready', ({ device_id }) => {
              const spotifyPlayer = new SpotifyPlayer(player, device_id, trackId, contextUri, token, true);
              resolve(spotifyPlayer);
            });
    
            player.addListener('not_ready', ({ device_id }) => {
              const spotifyPlayer = new SpotifyPlayer(player, device_id, trackId, contextUri, token, false);
              resolve(spotifyPlayer);
            });
    
            player.connect();
          } catch (err) {
            logError(err);
            resolve(new SpotifyPlayer(null, '', '', token, '', false));
          }
        };
      });
    };

And this is the test:

it('should initialize the Spotify SDK and return a SpotifyPlayer object', async () => {
    const token = 'abc123';
    const trackId = '123';
    const contextUri = 'spotify:album:456';
    const playbackStateChangeHandler = jest.fn();
    const errorHandler = jest.fn();

    const spotifyPlayer = await initializeSpotifySDK(
      token,
      trackId,
      contextUri,
      playbackStateChangeHandler,
      errorHandler
    );

    console.log({ spotifyPlayer });

    expect(spotifyPlayer).toBeInstanceOf(SpotifyPlayer);
    expect(spotifyPlayer.deviceId).toBeDefined();
    expect(spotifyPlayer.trackId).toEqual(trackId);
    expect(spotifyPlayer.contextUri).toEqual(contextUri);
    expect(spotifyPlayer.token).toEqual(token);
  });

The whole error

    ✕ should initialize the Spotify SDK and return a SpotifyPlayer object (5003 ms)

  ● spotifySdkService › should initialize the Spotify SDK and return a SpotifyPlayer object

    thrown: "Exceeded timeout of 5000 ms for a test.
    Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."

      108 |   });
      109 |
    > 110 |   it('should initialize the Spotify SDK and return a SpotifyPlayer object', async () => {
          |   ^
      111 |     const token = 'abc123';
      112 |     const trackId = '123';
      113 |     const contextUri = 'spotify:album:456';

      at services/spotifySdkService.spec.ts:110:3
      at Object.<anonymous> (services/spotifySdkService.spec.ts:17:1)
      at TestScheduler.scheduleTests (../node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (../node_modules/@jest/core/build/runJest.js:404:19)
      at _run10000 (../node_modules/@jest/core/build/cli/index.js:320:7)
      at runCLI (../node_modules/@jest/core/build/cli/index.js:173:3)

Any ideas on what I am doing wrong?

Upvotes: 0

Views: 5533

Answers (1)

Inigo
Inigo

Reputation: 15078

The error message is telling you exactly what's going wrong: the code you are testing is taking more than 5 seconds to complete, which isn't unexpected for something that is making a internet request.

  1. I would first do as the error suggests to make sure that your test functions, even if very slowly:

    jest.setTimeout(60000) // a whole minute!
    
  2. If it fails, bump it to 5 minutes and try again (and wait).

    If it works, and even if it doesn't, you can then try to isolate what exactly is taking so long (or not returning) by inserting timing measurements around code most likely taking a long time:

    const start = Date.now()
    console.log(`starting...`)
    player.connect()
    console.log(`elapsed millis: ${Date.now() - start}`)
    
    
  3. If you see starting... but never the elapse millis even after a long wait, then the code in between the two console log statements appears to be hanging somewhere.

  4. If you never even see starting... in the console, then either jest is suppressing console output or whatever is taking long is happening before the code you chose to measure.

    • Call your function from a plain script to take jest out of the picture. This will keep things simple and will uncover whether jest or how you're using it is the source of the problem (i doubt it0.

    • If you still don't see starting... then move the lines:

      const start = Date.now()
      console.log(`starting...`)
      

      to the top of your function.

    • If you still don't see it, you are doing something else wrong.

  5. If you see the elapsed time, and it is long, i.e. greater than 5000, narrow down which line it causing it by moving the timing statements. If it is a single function call to one of your functions, you can move the timing statements to the inside of that function and narrow the source in there.

I suspect player.connect() is what's taking so long, and that could be either normal or an issue with your internet connection, or perhaps your permissions/credential used in making the Spotify request.

Upvotes: 1

Related Questions