2017-05-28 34 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>