Files
json-server/test/cli/index.js
2015-07-15 18:44:33 +02:00

124 lines
2.9 KiB
JavaScript

var os = require('os')
var fs = require('fs')
var path = require('path')
var cp = require('child_process')
var request = require('supertest')
var rmrf = require('rimraf')
var pkg = require('../../package.json')
request = request('http://localhost:3000')
var tmpDir = path.join(__dirname, '../../tmp')
var dbFile = path.join(tmpDir, 'db.json')
var routesFile = path.join(tmpDir, 'routes.json')
function cli (args) {
var bin = path.join(__dirname, '../..', pkg.bin)
return cp.spawn('node', [bin].concat(args), {
stdio: 'inherit',
cwd: __dirname
})
}
/* global beforeEach, afterEach, describe, it */
describe('cli', function () {
var child
beforeEach(function () {
fs.mkdirSync(tmpDir)
fs.writeFileSync(dbFile, JSON.stringify({ posts: [] }))
fs.writeFileSync(routesFile, JSON.stringify({ '/blog/': '/' }))
})
afterEach(function (done) {
rmrf.sync(tmpDir)
child.kill()
setTimeout(done, 1000)
})
describe('db.json', function () {
beforeEach(function (done) {
child = cli([dbFile])
setTimeout(done, 1000)
})
it('should support JSON dbFile', function (done) {
request.get('/posts').expect(200, done)
})
})
describe('seed.js', function () {
beforeEach(function (done) {
child = cli(['fixtures/seed.js'])
setTimeout(done, 1000)
})
it('should support JS file', function (done) {
request.get('/posts').expect(200, done)
})
})
describe('http://jsonplaceholder.typicode.com/db', function () {
beforeEach(function (done) {
this.timeout(6000)
child = cli(['http://jsonplaceholder.typicode.com/db'])
setTimeout(done, 5000)
})
it('should support URL file', function (done) {
request.get('/posts').expect(200, done)
})
})
describe('db.json -r routes.json', function () {
beforeEach(function (done) {
child = cli([dbFile, '-r', routesFile])
setTimeout(done, 1000)
})
it('should use routes.json', function (done) {
request.get('/blog/posts').expect(200, done)
})
})
// FIXME test fails on OS X and maybe on Windows
// But manually updating db.json works...
if (os.platform() === 'linux') {
describe('--watch db.json -r routes.json', function () {
beforeEach(function (done) {
child = cli(['--watch', dbFile, '-r', routesFile])
setTimeout(done, 1000)
})
it('should watch db file', function (done) {
fs.writeFileSync(dbFile, JSON.stringify({ foo: [] }))
setTimeout(function () {
request.get('/foo').expect(200, done)
}, 1000)
})
it('should watch routes file', function (done) {
// Can be very slow
this.timeout(10000)
fs.writeFileSync(routesFile, JSON.stringify({ '/api/': '/' }))
setTimeout(function () {
request.get('/api/posts').expect(200, done)
}, 9000)
})
})
}
})