summaryrefslogtreecommitdiff
path: root/deps/npm/node_modules/find-npm-prefix/test/find-prefix.js~
blob: 76886cec678c5385d8e6abcd597fa0cf7b53f30d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
'use strict'
const Bluebird = require('bluebird')
const test = require('tap').test
const requireInject = require('require-inject')
const findPrefix = requireInject('../find-prefix.js', {
  fs: {
    readdir: mockReaddir
  }
})

test('find-prefix', t => {
  const tests = {
    '/Users/example/code/test1/node_modules': '/Users/example/code/test1',
    '/Users/example/code/test1/node_modules/node_modules': '/Users/example/code/test1',
    '/Users/example/code/test1/sub1': '/Users/example/code/test1',
    '/Users/example/code/test1/sub1/sub1a': '/Users/example/code/test1',
    '/Users/example/code/test2': '/Users/example/code/test2',
    '/Users/example/code/test2/sub2': '/Users/example/code/test2',
    '/Users/example/code': '/Users/example/code',
    '/Users/example': '/Users/example',
    '/does/not/exist': '/does/not/exist'
  }
  t.plan(Object.keys(tests).length)
  return Bluebird.map(Object.keys(tests), dir => {
    return findPrefix(dir).then(pre => {
      t.is(pre, tests[dir], dir)
    })
  })
})

test('fail-prefix', t => {
  return findPrefix('/Users/example/eperm').then(pre => {
    t.fail('no eperm')
  }).catch(err => {
    t.is(err.code, 'EPERM', 'got perm error')
  })
})

const fixture = {
  'Users': {
    'example': {
      'code': {
        'test1': {
          'node_modules': {
            'node_modules': {}
          },
          'sub1': {
            'sub1a': {}
          }
        },
        'test2': {
          'package.json': {},
          'sub2': {}
        }
      }
    }
  }
}

function mockReaddir (dir, cb) {
  if (/eperm/.test(dir)) {
    const err = new Error('Can not read: ' + dir)
    err.code = 'EPERM'
    return cb(err)
  }
  const parts = dir.split(/\//).slice(1)
  let cwd = fixture
  let part
  while (part = parts.shift()) {
    if (part in cwd) {
      cwd = cwd[part]
    } else {
      const err = new Error('Does not exist: ' + dir + ' * ' + part)
      err.code = 'ENOENT'
      return cb(err)
    }
  }
  return cb(null, Object.keys(cwd))
}