【发布时间】:2015-08-13 13:22:00
【问题描述】:
我想测试我的 Web 应用程序如何处理服务器响应。这就是为什么我创建了一个使用Sinon.JS to fake a server 的测试场景。
我的应用程序代码发出两个请求,在我的测试场景中,我想强制在第二个请求的响应之后发送对第一个请求的响应。
顺序:
- 请求 1
- 请求 2
- 响应 2
- 响应 1
这是我为测试用例编写的 CoffeeScript 代码:
# Request 1
server.respondWith 'GET', "http://localhost/endpoint", [200, {"Content-Type": "application/json"}, '{"A":"A"}']
# Request 2
server.respondWith 'GET', "http://localhost/endpoint", [200, {"Content-Type": "application/json"}, '{"B":"B"}']
# My application code
...
# Response 1
server.respond()
# Response 2
server.respond()
一旦我开始测试,从我的应用程序代码对http://localhost/endpoint 的所有 REST 调用都会得到相同的响应 ({"B":"B"})。所以在我看来,Sinon.JS 总是从使用respondWith 定义的最后一个 URL 映射中获取响应。
但我希望我的伪造服务器将{"B":"B"} 返回到http://localhost/endpoint 的第一次命中。在第二次点击时,它应该返回 {"A":"A"}。
有可能做这样的事情吗?
# Request 1
request_1 = server.respondWith 'GET', "http://localhost/endpoint", [200, {"Content-Type": "application/json"}, '{"A":"A"}']
# Request 2
request_2 = server.respondWith 'GET', "http://localhost/endpoint", [200, {"Content-Type": "application/json"}, '{"B":"B"}']
# My application code (makes multiple requests to the same endpoint)
...
# Response 1
request_2.respond()
# Response 2
request_1.respond()
【问题讨论】:
标签: javascript mocking jasmine integration-testing sinon