Thursday, 18 May 2017

Is it possible to call npm CLI app's main JS file as if it was ran within a subfolder?

I have a small npm CLI library which fixes errors in changelog.md's sitting at the same directory where CLI is called. I'm trying to write at least one unit test for it's CLI part (its API is a separate library and it's well-tested).

It's easy to trigger CLI's main JS file using execa library, like:

execa.sync('./cli.js')

but how do you trigger cli.js sitting in a root and meant to be looking for a ./changelog.md in a root, to execute on a different test file in a subfolder (/test/changelog.md)?

Mind you, there's real changelog.md file in the root which has nothing to do with unit test.

(Worst case scenario, we could copy cli.js into /test/, call it there via execa and delete later, but this looks not DRY solution)


My current AVA unit test is below. seed is incorrect changelog.md file. intended is correct changelog.md against which we'll compare later. I write seed contents into /test/changelog.md and want to run a CLI on it. Problem: how do I run ./cli.js against /test/package.json? Mind you, I still want my CLI API to be simple, not accept any arguments with paths (what could be a last resort solution — to accept custom path arguments).

My current test is nearly there, but it runs against root, ./package.json contents, not /test/package.json (which is how API would behave for end-user):

import path from 'path'
import fs from 'fs'
import test from 'ava'
import execa from 'execa'

test('01.01 - reads and writes correctly', t => {
  var seed = fs.readFileSync(path.join('test', 'seed.md'), 'utf8')
  var intended = fs.readFileSync(path.join('test', 'intended.md'), 'utf8')
  fs.writeFileSync(path.join('test', 'changelog.md'), seed, 'utf8')

  execa.sync('./cli.js') // <<< PROBLEM, this runs on root, not on ./test/changelog.md!

  t.deepEqual(
    fs.readFileSync(path.join('test', 'changelog.md'), 'utf8'),
    intended,
    '01.01'
  )
})

How do you execute an npm CLI package on a different directory when unit testing, if it's meant to be ran on file present at the same level as CLI's JS file?

Thank you.



via revelt

No comments:

Post a Comment