title: Jest how to test asynchronous load script
body: <p>I have a tool for asynchronously loading scripts, using jest for asynchronous testing, but jest has timed out and can't respond to scripts. How do I implement this feature?</p>
  
  <p>I tried to write a test sample according to the promise of the document</p>
  
  <p>This is my script loader code and Jest test code</p>
  
  <pre class="lang-js prettyprint-override"><code>function mapLoader(key, version, url) {
    return new Promise((resolve, reject) =&gt; {
      if (AMap) {
        return resolve(AMap);
      }
  
      if (!url &amp;&amp; (!key || !version)) {
        warn('The parameter is incorrect and must contain the url attribute or the key and version attributes.');
      }
  
      const aMapUrl = url || `${defaultPath}?v=${version}&amp;key=${key}`;
  
      const jsApi = document.createElement('script');
      jsApi.charset = 'utf-8';
      jsApi.src = aMapUrl;
      jsApi.onerror = reject;
      jsApi.onload = () =&gt; {
        if (window.AMap) {
          AMap = window.AMap;
          // 如果不加上 setTimeout 在本地开发时，会有一定几率导致刷新页面覆盖物无法显示在地图上。
          setTimeout(() =&gt; {
            resolve(AMap);
          }, 0);
        } else {
          warn('AMap SDK Load Failure.');
        }
      };
  
      document.head.appendChild(jsApi);
    });
  }
  </code></pre>
  
  <pre class="lang-js prettyprint-override"><code>test('test mapLoader function', () =&gt; {
    return mapLoader('d2d76e2274bf5973ecfb1f68454b6f3b', '1.4.15').then(AMap =&gt; {
      expect(AMap).toBe('peanut butter');
    });
  });
  </code></pre>
  
  <blockquote>
    <p>Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:</p>
  </blockquote>