LoginSignup
5
6

More than 5 years have passed since last update.

sinon.fakeServer は 正規表現が使える

Last updated at Posted at 2014-01-31

sinon.fakeServerはクロスドメインとかクエリパラメータの一致を定義するの面倒とか考えてググってたらやっぱり正規表現が書けた。

Sinon.JS - Documentation

server.respondWith(/\/todo-items\/(\d+)/, function (xhr, id) {
    xhr.respond(200, { "Content-Type": "application/json" }, '[{ "id": ' + id + ' }]');
});

最終的にこんな感じのヘルパを用意した

stubRequest = ({pattern, method, status, response}) ->
  beforeEach ->
    throw 'pattern is required' unless pattern
    method ?= 'GET'
    status ?= 200
    response ?= {}

    unless @_server
      @_server = sinon.fakeServer.create()
      @_server.autoRespond = true

    @_server.respondWith(method, pattern,
      [
        status
        {"Content-Type": "application/json"}
        JSON.stringify(response)
      ]
    )

  afterEach: ->
    @_server?.restore?()

こうやって使う

describe 'Commit', ->
  beforeEach ->
    @commit = new Commit
  stubRequest
    pattern: /\/api\/commit/
    method: 'POST'

  it 'should post /api/commit', (done) ->
    @commit.commit().done => done()

便利

5
6
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
6