如何使用Polymer iron-ajax编写API测试

时间:2019-06-27 16:37:25

标签: polymer mocha chai sinon

我试图使用Mocha测试套件在Polymer 2.x中生成一个iron-ajax请求并对其响应进行测试。

但是,运行此测试时,出现以下错误:

  

无法读取未定义上下文的属性“ generateRequest”。在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>

如何在此框架中提出AJAX请求并处理响应?

1 个答案:

答案 0 :(得分:2)

我建议为此使用fetch。它还会发送ajax调用,它是您的浏览器的本地功能。


<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>