我最难模拟服务器对自定义组件中的 Iron-ajax 组件的响应。这是我的代码文件。
自定义组件.html:
<link rel="import" href="/iron-ajax/iron-ajax.html">
<link rel="import" href="/internal-component/internal-component.html">
<dom-module id="custom-component">
<template>
<iron-ajax url="staticFile.json" auto handle-as="json" last-response={{ajaxResponse}}></iron-ajax>
<template is="dom-repeat"
items={{ajaxResponse}}
sort="_sort"
id="gridRow">
<internal-component var1={{item.var1}}
var2={{item.var2}}>
</internal-component>
</template>
</template>
</dom-module>
<script>(some cool scripts that are working...)</script>
自定义组件-tests.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="/webcomponentsjs/webcomponents-lite.js"></script>
<script src="/web-component-tester/browser.js"></script>
<script src="/test-fixture/test-fixture-mocha.js"></script>
<link rel="import" href="/test-fixture/test-fixture.html" />
<link rel="import" href="/polymer/polymer.html">
<link rel="import" href="/polymer-ts/polymer-ts.html">
<link rel="import" href="custom-component.html">
</head>
<body>
<test-fixture id="testElement">
<template>
<custom-component></custom-component.>
</template>
</test-fixture>
<script>
suite('<custom-component>', function () {
var testElement;
var server;
var responseHeaders = {
json: { 'Content-Type': 'application/json' },
plain: { 'Content-Type': 'text/plain' }
};
setup(function () {
replace('custom-component').with('fake-custom-component');
server = sinon.fakeServer.create();
server.respondWith('GET', /staticFile\.json/, [
200,
responseHeaders.json,
'[{"var1": "9a","var2": "17n"}]'
]);
testElement = fixture("testElement");
});
teardown(function () {
server.restore();
});
suite('testSuite', function () {
test('test1', function () {
var ajax = testElement.getElementsByTagName('iron-ajax')[0];
ajax.lastResponse = null;
ajax.generateRequest();
server.respond();
assert(ajax.lastResponse.hour === "9a");
});
});
});
</script>
</body>
</html>
您会注意到我明确地调用了 iron-ajax generateRequest,因为如果我没有这样做,那么在我的测试完成(并且失败)之前,该请求甚至不会发生。当显式调用 generateRequest 时,我至少能够使请求发生,但是(即使我正在调用 server.respond())iron-ajax 直到测试完成后才会调用 _handleResponse。而且,即使这样做,它也不会设置 lastResponse ,因为在 iron-ajax 中有一行代码检查是否 (request === this.lastRequest) (它不是)。
我究竟做错了什么?