|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +let os = require('os'); |
| 4 | +let path = require('path'); |
| 5 | +let fs = require('fs'); |
| 6 | +let test = require('tape'); |
| 7 | +let writejson = require('..'); |
| 8 | + |
| 9 | +let tmp = os.tmpdir(); |
| 10 | +let name = path.join(tmp, String(Math.random())); |
| 11 | +let json = { |
| 12 | + hello: 'world' |
| 13 | +}; |
| 14 | + |
| 15 | +test('writejson: should write json data to file', t => { |
| 16 | + writejson(name, json, error => { |
| 17 | + t.notOk(error, 'no write error'); |
| 18 | + |
| 19 | + fs.readFile(name, 'utf8', (error, data) => { |
| 20 | + t.notOk(error, 'no read error'); |
| 21 | + t.deepEqual(json, JSON.parse(data), 'data should be equal'); |
| 22 | + |
| 23 | + fs.unlink(name, error => { |
| 24 | + t.notOk(error, 'no remove error'); |
| 25 | + t.end(); |
| 26 | + }); |
| 27 | + }); |
| 28 | + }); |
| 29 | +}); |
| 30 | + |
| 31 | +test('writejson: no args', t => { |
| 32 | + t.throws(writejson, /name should be string!/, 'name check'); |
| 33 | + t.end(); |
| 34 | +}); |
| 35 | + |
| 36 | +test('writejson: no json', t => { |
| 37 | + let fn = () => writejson('hello'); |
| 38 | + |
| 39 | + t.throws(fn, /json should be object!/, 'json check'); |
| 40 | + t.end(); |
| 41 | +}); |
| 42 | + |
| 43 | +test('writejson: no callback', t => { |
| 44 | + let fn = () => writejson('hello', [1,2,3]); |
| 45 | + |
| 46 | + t.throws(fn, /callback should be function!/, 'callback check'); |
| 47 | + t.end(); |
| 48 | +}); |
| 49 | + |
| 50 | +test('writejson.sync: should write json data to file synchonously', t => { |
| 51 | + writejson.sync(name, json); |
| 52 | + let data = fs.readFileSync(name, 'utf8'); |
| 53 | + t.ok(data, 'data should be read'); |
| 54 | + t.deepEqual(json, JSON.parse(data), 'data should be equal'); |
| 55 | + fs.unlinkSync(name); |
| 56 | + t.end(); |
| 57 | +}); |
| 58 | + |
| 59 | +test('writejson.sync: no args', t => { |
| 60 | + t.throws(writejson.sync, /name should be string!/, 'name check'); |
| 61 | + t.end(); |
| 62 | +}); |
| 63 | + |
| 64 | +test('writejson.sync: no json', t => { |
| 65 | + let fn = () => writejson.sync('hello'); |
| 66 | + |
| 67 | + t.throws(fn, /json should be object!/, 'json check'); |
| 68 | + t.end(); |
| 69 | +}); |
| 70 | + |
| 71 | +test('writejson.sync.try: no args', t => { |
| 72 | + t.throws(writejson.sync.try, /name should be string!/, 'name check'); |
| 73 | + t.end(); |
| 74 | +}); |
| 75 | + |
| 76 | +test('writejson.sync.try: no json', t => { |
| 77 | + let fn = () => writejson.sync.try('hello'); |
| 78 | + |
| 79 | + t.throws(fn, /json should be object!/, 'json check'); |
| 80 | + t.end(); |
| 81 | +}); |
0 commit comments