1.0.1 • Published 6 years ago

node-capture v1.0.1

Weekly downloads
4
License
ISC
Repository
github
Last release
6 years ago

node-capture

Easily mock API in your tests.

Description

It will fork an express server on port you defined You can create mock api similar to what you did on express.js

const mockApi = new Capture(3001, 'api')
mockApi.onPost('/create', (req)=>{
  assert(req.body == 'EXAMPLE')
  mockApi.kill()
})
mockApi.onListen(()=>{ 
  // Your api calls here
  request({method:'POST', uri:'http://localhost:3001/api/create', body: 'EXAMPLE')
})

Example of testing incoming request

Mock an api server at localhost:3000/api/test to return JSON {hello:'world'} with status code 200

// Sample mocha test case
it(`MyGreatMethod should return {hello:'world'}`, function(done){
  // Your test target
  const myGreatMethod = function(){
    request({
      method: 'POST', 
      uri:`http://localhost:${port}/api/test`, 
      body:{hello:'world'}, 
      json:true
    })
  }

  let capture = new Capture(port, 'api')
  capture.onPost('test', function(req, res){
    capture.kill(done) // tell mockserver to stop
    assert(JSON.parse(req.body).hello === 'world') // Test your target really give result you expected
  })

  capture.onListen(function(){  // mock server is ready here
    myGreatMethod()
  })
})

Example of mocking response

const mockApi = new Capture(3001, 'api')
mockApi.onPost('/create', (req, res)=>{
  res.json({status:true})
})

mockApi.onListen(()=>{ 
  request({
    method:'POST', 
    uri:`http://localhost:${port}/api/create`, 
    body:'', 
  }, (err,res,body)=>{
    capture.kill(done)
    assert(JSON.parse(body).status===true)
  })
})

Example to use with wdio

const assert = require('assert');
const Capture = require('./capture')

describe('User create form in Index Page', ()=>{
  it('should POST my :name at /api/user/create', done => {
    let capture = new Capture(3000, 'api') // listen at port 3000 with URL prefix /api
    browser.url('/'); // This page has a form with a name Input field

    // accept POST on '/user/create' and response with {status:true}
    capture.onPost('/user/create', (request, res) => {
      capture.kill(done) 
      res.json({status:true})
      assert(request == {name:'roy'})
    })
    
    // ... 
    // code for browser automation to 
    // fill in the form with name = roy 
    // and do AJAX submit
  })
})