如何使用 lein doo phantom 使用 cljs-http 测试 http 请求

How to test http requests with cljs-http using lein doo phantom

当 运行使用 lein doo phantom 进行测试时,我收到了一个 -1 状态响应和一个空字符串作为正文。但是,当我 运行 在 repl 中进行测试时,我能够使用 200 状态响应和正文中的适当数据检索请求数据。这是因为如下所述首先返回了 manytomany 频道,从而给我不恰当的回应吗?如果是这样,我该如何解释呢?

https://github.com/r0man/cljs-http#async-response-handling

我还想也许我需要使用超时来等待请求完成。如果是这样,我将如何在我现有的代码中适当地应用它?看起来 cljs-http 有 :timeout 作为参数,但我无法让它正常工作(假设这是问题的原因)。

(deftest test-async
 (async done
      (go (let [response (<! (http/get "http://localhost:3000/api/user/1"
                                          {:with-credentials? false
                                           :query-params {"id" 1}}))]
            (is (= {:status 200}
                   (select-keys response [:status]))))
          (done))))

因为你是运行你在phantomjs下的测试。 Phantomjs 默认禁用跨域 XHR 访问并且您的测试 js 在本地主机上 运行,所有外部 ajax 调用都被拒绝。

您可以设置 --web-security=false 以允许您的测试进行跨域 ajax。

在你的project.clj中添加这个

:doo {:paths {:phantom "phantomjs --web-security=false"}}

关于 phantomjs 的更多信息

http://phantomjs.org/api/command-line.html