• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict'
2const Bluebird = require('bluebird')
3const test = require('tap').test
4const requireInject = require('require-inject')
5const findPrefix = requireInject('../find-prefix.js', {
6  fs: {
7    readdir: mockReaddir
8  }
9})
10
11test('find-prefix', t => {
12  const tests = {
13    '/Users/example/code/test1/node_modules': '/Users/example/code/test1',
14    '/Users/example/code/test1/node_modules/node_modules': '/Users/example/code/test1',
15    '/Users/example/code/test1/sub1': '/Users/example/code/test1',
16    '/Users/example/code/test1/sub1/sub1a': '/Users/example/code/test1',
17    '/Users/example/code/test2': '/Users/example/code/test2',
18    '/Users/example/code/test2/sub2': '/Users/example/code/test2',
19    '/Users/example/code': '/Users/example/code',
20    '/Users/example': '/Users/example',
21    '/does/not/exist': '/does/not/exist'
22  }
23  t.plan(Object.keys(tests).length)
24  return Bluebird.map(Object.keys(tests), dir => {
25    return findPrefix(dir).then(pre => {
26      t.is(pre, tests[dir], dir)
27    })
28  })
29})
30
31test('fail-prefix', t => {
32  return findPrefix('/Users/example/eperm').then(pre => {
33    t.fail('no eperm')
34  }).catch(err => {
35    t.is(err.code, 'EPERM', 'got perm error')
36  })
37})
38
39const fixture = {
40  'Users': {
41    'example': {
42      'code': {
43        'test1': {
44          'node_modules': {
45            'node_modules': {}
46          },
47          'sub1': {
48            'sub1a': {}
49          }
50        },
51        'test2': {
52          'package.json': {},
53          'sub2': {}
54        }
55      }
56    }
57  }
58}
59
60function mockReaddir (dir, cb) {
61  if (/eperm/.test(dir)) {
62    const err = new Error('Can not read: ' + dir)
63    err.code = 'EPERM'
64    return cb(err)
65  }
66  const parts = dir.split(/\//).slice(1)
67  let cwd = fixture
68  let part
69  while ((part = parts.shift())) {
70    if (part in cwd) {
71      cwd = cwd[part]
72    } else {
73      const err = new Error('Does not exist: ' + dir + ' * ' + part)
74      err.code = 'ENOENT'
75      return cb(err)
76    }
77  }
78  return cb(null, Object.keys(cwd))
79}
80