LoginSignup
5
0

More than 5 years have passed since last update.

nock の使い方メモ

Posted at

概要

node のユニットテストでサーバーをモックするために、リクエストをフックして任意のレスポンスを返す時に、nock が便利です。

いつも使い方を忘れるのでよくある使い方をメモします。

使い方

POST https://example.com/api/foo/bar へリクエストを出す Promise を返す関数 doFooBar をテストします。

/api/foo/bar のリクエストに対して一度だけ 200 を返し、scope.isDone が true になります。

const { doFooBar } = require("../fooClient")
const nock = require("nock")

describe("fooClient", () => {
  describe("doFooBar", function() {
    // API サーバーをモックする
    const scope = nock("https://example.com")
      .post("/api/foo/bar")
      .reply(200, "OK")

    it("should request api", () =>
      doFooBar("hoge fuga")
        .then(() => {
          // /api/foo/bar にリクエストを出した
          assert(scope.isDone)
        })
    )

注意点

nock は一つのモックを一回だけ実行するので、仮に doFooBar が2回リクエストを出すと、2度目は必ず失敗になります。

テストコードを通して何度も叩く場合などにモックしたままにするには、persist() を設定する必要があります。この場合、一度目のリクエストで isDone が true になります。

const { doFooBar } = require("../fooClient")
const nock = require("nock")

describe("fooClient", () => {
  describe("doFooBar", function() {
    // API サーバーをモックする
    const scope = nock("https://example.com")
      .post("/api/foo/bar")
      .persist()
      .reply(200, "OK")

    it("should request api", () =>
      doFooBar("hoge fuga")
        .then(() => {
          // /api/foo/bar にリクエストを1回以上出した
          assert(scope.isDone)
        })
    )
5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0