3

私はまだ Cljs と Om の学習段階にあります。コンポーネントテストの作成を検討しています。一部のコンポーネントにcljs-httpは、私が作成した API への呼び出しがあります。テストするとき、これらの API 呼び出しで実際にリクエストを送信したくないので、リクエストをモックしてフィクスチャを返すことを検討しています。私が持っているコンポーネントの例を次に示します。

(defn async-component [data owner]
  (reify
    IWillMount
    (will-mount [_]
      (let [resp (go ((<! (async-call "/") :body))]
        (om/update! data [:objects] resp)))
    IRender
    (render [_]
      [:ul
        (om/build-all item-component data)])))

(defn async-call [path]
  (http/get path {:keywordize-keys true}))

コードが実際に構文的に正しいかどうか気にしないでください。要点を示しているだけです。

ここでやりたいことはasync-component、これと API 呼び出しをテストして、リクエストをモックするフィクスチャがレンダリングされるかどうかを確認することです。これはどのように行われますか?非同期コードをテストするためのブロックがあることは知っcljs.testていますが、すべての例は、より大きなコンテキストではなく、その中にasyncのみ含まれる実際のコード ブロックをテストすることを示しています。go

4

1 に答える 1

5

コンポーネントをテストするためにモックを使用する方法を次に示します。

(deftest test-async-component
  (cljs.test/async done
    (with-redefs
      [async-call (fn [path]
                    (let [mock-ch (async/chan 1)
                          fixture-data {:body {:fixture-with path :and "foobar"}})]
                      (async/put! mock-ch fixture-data)
                      mock-ch)]
      ; At this point we successfully mocked out our data source (the API call)
      ; the only task that remains is to render our Om component into DOM and inspect it.
      ; As this task requires utility fns I will reuse the ones in this blog post:
      ; http://lab.brightnorth.co.uk/2015/01/27/unit-and-browser-testing-om-clojurescript-applications/

      (let [c (new-container!)
            initial-data {:objects [{:initial-object 42}]}]
        ; This will mount and render your component into the DOM residing in c.
        (om/root async-component initial-data {:target c})

        (testing "fixture data gets put into the DOM"
          (is (= "foobar" (text (sel1 c :ul)))))

        ; You can add more tests in this manner, then finally call 'done'.
        (done)))))

上記の英語のコードで実行される手順は次のとおりです。

  1. async-callフィクスチャ データが事前に入力されたチャネル (元のインターフェイスと同じインターフェイス) を返すWriteのモック fn。
  2. 元の fn をモック化します (それを参照するか、ns を完全に修飾する必要があります)。
  3. 単体テスト用に新しい仮想 DOM を作成します。
  4. API から取得されていないモック データがある場合は、それを指定します。
  5. コンポーネントを DOM にレンダリングします (これは実行async-call時に呼び出され、 が削除されます)。om/will-mountfixture-datachan
  6. DOM の内容を観察します。
于 2016-01-11T23:43:28.243 に答える