2017-05-28 26 views
2

我正在寫一個聚合物應用程序,並有聚合物元素使用的服務。我想測試這個服務,但不知道如何。如何測試聚合物中的服務?

下面是我在服務:

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

<link rel="import" href="../test-service.html"> 

<script> 
define('test-service',() => { 
    class TestService { 
    constructor(componentA, componentB) { 
     this.componentA = componentA; 
     this.componentB = componentB; 
    } 
    } 
    return TestService; 
}); 
</script> 

如何測試呢?如果我嘗試簡單包含.html文件,我無法訪問TestService。

+0

您是否嘗試過'web-component-tester'? – a1626

+0

是的,這就是我正在使用的以及我的麻煩源於哪裏。我相應地更新了我的問題描述。 – horstwilhelm

回答

0

終於搞明白了。這一切都與聚合物IMD和依賴注入有關。定義一個測試套件看起來不一樣:

define('test-service-test', ['test-service'], (TestService) => { 
    let testServiceInstance = new TestService(1, 2); 

    test('basic test', function(){ 
     assert.equal(testServiceInstance.componentA, 1); 
     assert.equal(testServiceInstance.componentB, 2); 
    }) 
}); 
0

這是一個示例測試的完整html。基本上通過test-fixture添加您的測試服務標籤,然後查看它是否正常工作。

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes"> 

    <title>test-service test</title> 

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

    <link rel="import" href="../test-service.html"> 
</head> 
<body> 

<test-fixture id="BasicTestFixture"> 
    <template> 
     <test-service></test-service> 
    </template> 
</test-fixture> 

<script> 
    suite('test-service', function() { 

     test('instantiating the element with default properties works', function() { 
      let testService = fixture('BasicTestFixture'); 
      assert.equal(testService.apiUrl, 'http://myapi.domain.com'); 
      // possible something like 
      // let addResult = testService.addElement(...); 
      // assert.equals(addResult, '{"result": "success"}'); 
     }); 

    }); 
</script> 

</body> 
</html>