Skip to content

Instantly share code, notes, and snippets.

@g-k
Created September 21, 2012 03:45
Show Gist options
  • Save g-k/3759615 to your computer and use it in GitHub Desktop.
Save g-k/3759615 to your computer and use it in GitHub Desktop.
Note on exposing a required module to test it.

I ran into some trouble writing jasmine unit tests for request.pipe today.

Exposing the request module instead of modifying require or stubbing request was easiest:

# actions.coffee
request = require 'request'

module.exports = 
  feed: (request, response) ->
    request.get("http://www.joyent.com/blog/feed").pipe res

  # Export request module so we can test piping
  _request: request

# actions_spec.coffee
actions = require "./actions"

describe 'When I request the feed', ->

  beforeEach ->
    @req = 'request'
    @res = 'response'

    @pipe = jasmine.createSpy('pipe').andReturn @res

    spyOn(actions._request, 'get').andReturn(
      pipe: @pipe
    )

  it 'should pipe feed data', ->
    actions.feed @req, @res

    url = 'http://www.joyent.com/blog/feed'

    expect(actions._request.get).toHaveBeenCalledWith url
    expect(@pipe).toHaveBeenCalledWith @res

This does unnecessarily tie the behavior of fetching and forwarding a feed to an implementation using the request module.

I looked into testing only the behavior with nock, but only read the project readme. It looks like nock does support piping.

Google is my friend.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment