nock: Problem trying to intercept a request

Sorry if that is not the best to ask this.

But i am trying to use nock to mock the Shopify´s API, then i have some like this to get all blogs from a shop:

class Blog
  constructor: (key, pass, shop) ->
    throw new Error 'Blog missing parameters' if not pass? or not key? or not shop?
    @options =
      host: "http://#{key}:#{pass}@#{shop}.myshopify.com"
      port: 80
      method: "GET"
      path: '/admin/blogs.json'

  all: (cb) ->
    req = request @options, (res) ->
      response = ""
      res.setEncoding('utf8')
      res.on 'data', (data) ->
        response += data
      res.on 'end', ->
        error = new Error 'Request Error #{res.statusCode}' unless res.statusCode is 200
        process.nextTick ->
          cb(error, JSON.parse(response))
    req.end()

And parts of my testing they are some like this:

describe 'Receive a list of all Blogs', ->
    before ->
      @fixture = loadFixture 'blog/blogs'
      @api = nock "https://#{KEY}:#{PASSWORD}@#{STORE}.myshopify.com"
      @blog = new Blog KEY, PASSWORD, STORE


    it 'should be possible get a list of all blog like an Array', (done) ->
      @api.get('/admin/blogs.json').reply(200, @fixture)
      @blog.all (err, blogs) =>
        @api.done()
        blogs.should.be.an.instanceof Object
        done()

Sorry but i dont know what is wrong in my code, because allways get the response from the real server. But i need that my calls they are intercepting by nock to response my @fixture arrays of blogs.

Again sorry for ask that here.

About this issue

  • Original URL
  • State: closed
  • Created 12 years ago
  • Comments: 23 (12 by maintainers)

Most upvoted comments

Sorry it’s just super hard for me to read coffeescript, I don’t understand it

Canonical example, in javascript:

dscape at air in ~/Desktop/nock_test 
$ node index.js n
{"ok":true}
dscape at air in ~/Desktop/nock_test 
$ cat index.js 
var nock    = require('nock')
  , request = require('request')
  ;

nock('http://www.google.com')
  .get('/')
  .reply(200, {ok:true}, {})
  ;

request.get('http://www.google.com', function (_,_,b) { console.log(b); });

Then require('nock') has to happen before your app is initialized. There is nothing nock can do if you don’t, since we need to appear first so that the http.request function gets wrapped.