選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

test-config.js 2.2 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. const fs = require('fs')
  2. const t = require('tap')
  3. const sinon = require('sinon')
  4. const dotenv = require('../lib/main')
  5. const mockParseResponse = {test: 'foo'}
  6. let readFileSyncStub
  7. t.beforeEach(done => {
  8. readFileSyncStub = sinon.stub(fs, 'readFileSync').returns('test=foo')
  9. sinon.stub(dotenv, 'parse').returns(mockParseResponse)
  10. done()
  11. })
  12. t.afterEach(done => {
  13. readFileSyncStub.restore()
  14. dotenv.parse.restore()
  15. done()
  16. })
  17. t.test('takes option for path', ct => {
  18. ct.plan(1)
  19. const testPath = 'tests/.env'
  20. dotenv.config({path: testPath})
  21. ct.equal(readFileSyncStub.args[0][0], testPath)
  22. })
  23. t.test('takes option for encoding', ct => {
  24. ct.plan(1)
  25. const testEncoding = 'base64'
  26. dotenv.config({encoding: testEncoding})
  27. ct.equal(readFileSyncStub.args[0][1].encoding, testEncoding)
  28. })
  29. t.test('reads path with encoding, parsing output to process.env', ct => {
  30. ct.plan(2)
  31. const res = dotenv.config()
  32. ct.same(res.parsed, mockParseResponse)
  33. ct.equal(readFileSyncStub.callCount, 1)
  34. })
  35. t.test('makes load a synonym of config', ct => {
  36. ct.plan(2)
  37. const env = dotenv.load()
  38. ct.same(env.parsed, mockParseResponse)
  39. ct.equal(readFileSyncStub.callCount, 1)
  40. })
  41. t.test('does not write over keys already in process.env', ct => {
  42. ct.plan(2)
  43. const existing = 'bar'
  44. process.env.test = existing
  45. // 'foo' returned as value in `beforeEach`. should keep this 'bar'
  46. const env = dotenv.config()
  47. ct.equal(env.parsed.test, mockParseResponse.test)
  48. ct.equal(process.env.test, existing)
  49. })
  50. t.test('does not write over keys already in process.env if the key has a falsy value', ct => {
  51. ct.plan(2)
  52. const existing = ''
  53. process.env.test = existing
  54. // 'foo' returned as value in `beforeEach`. should keep this ''
  55. const env = dotenv.config()
  56. ct.equal(env.parsed.test, mockParseResponse.test)
  57. // NB: process.env.test becomes undefined on Windows
  58. ct.notOk(process.env.test)
  59. })
  60. t.test('returns parsed object', ct => {
  61. ct.plan(2)
  62. const env = dotenv.config()
  63. ct.notOk(env.error)
  64. ct.same(env.parsed, mockParseResponse)
  65. })
  66. t.test('returns any errors thrown from reading file or parsing', ct => {
  67. ct.plan(1)
  68. readFileSyncStub.throws()
  69. const env = dotenv.config()
  70. ct.type(env.error, Error)
  71. })