Search code examples
polymermocha.jschaisinon

How to write an API test with Polymer iron-ajax


I am trying to generate an iron-ajax request and run a test on its response in Polymer 2.x with using the Mocha test suite.

However, when running this test I get the following error:

Cannot read property 'generateRequest' of undefined Context. at my-test.html:25

<!doctype html>

<html> 
<head>
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
  <title>shop-catalogs</title>

  <script src="/bower_components/webcomponentsjs/webcomponents-lite.js"></script>
  <script src="/bower_components/web-component-tester/browser.js"></script>
  <script src="/bower_components/web-component-tester/data/a11ySuite.js"></script>

  <!-- Import the element(s) to test -->
  <link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">
  <script src="/bower_components/mocha/mocha.js"></script>

</head>
<body>

  <test-fixture id="ajax">
    <template>
      <iron-ajax
        handle-as="json" 
        headers$='{"Authorization": "Bearer api_access_token"}'
        method="get"
        url="https://api.com/test/endpoint">
      </iron-ajax>
    </template>
  </test-fixture>

  <script>
    suite('shop-catalogs tests', () => {
      var ajax;

      test('checking for AJAX response', () => {

        let request = ajax.generateRequest();
        request.completes.then(response => {
          console.log(response);
        })

      });

    });
  </script>

</body>
</html>

How can I make an AJAX request and handle the response in this framework?


Solution

  • I would advice to use fetch for this. It also will send an ajax call and is native to your browser.

    
    <html> 
    <head>
      <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
      <title>shop-catalogs</title>
    
      <script src="/bower_components/webcomponentsjs/webcomponents-lite.js"></script>
      <script src="/bower_components/web-component-tester/browser.js"></script>
      <script src="/bower_components/web-component-tester/data/a11ySuite.js"></script>
    
      <!-- Import the element(s) to test -->
      <script src="/bower_components/mocha/mocha.js"></script>
    
    </head>
    <body>
      <script>
        suite('shop-catalogs tests', () => {
          test('checking for AJAX response', (done) => {
            fetch("https://api.com/test/endpoint", {
                headers: {"Authorization": "Bearer api_access_token"}
            }).then(res => {
                assert.equal(res.status, 200)
                return res.json()
            })
            .finally(res=>{ 
                console.log(res)
                done()//async test needs to tell when done 
            })
          });
    
        });
      </script>
    
    </body>
    </html>