简体   繁体   中英

Testing of npm scripts

How can I write a test that npm scripts run successfully?

I have npm scripts in package.json as follows.

  "scripts": {
    "start": "node server.js",
    "dev": "webpack serve --mode development",
    "lint": "eslint src",
    ...

I'd like to test these npm scripts launch successfully.

For example, how do I test the command npm run dev ( webpack serve ) launches successfully?

You test them like you test a computer process - independent of JavaScript. You treat the fact webpack/eslint are JavaScript programs as an implementation detail.

Basically - they should only be tested in really really big projects and have a few tests.

A test can look something like:

const util = require('util');
const { exec } = util.promisify(require('child_process').exec);

describe('your run scripts', () => {
  it('starts a dev server', () => {
     // create a way to stop the server
     const ac = new AbortController(); 
     // start the dev server
     const devServerPromise = exec('npm run dev', { signal: ac.signal });
     // validate the server launched (retry comes from any promise retry package, fetch can be unidici or axios just the same)
     // localhost:4200 is an example for where the dev server is running
     await retry(() => fetch('http://localhost:4200/'));
     ac.abort(); // close the dev erver
  });
});

Note that like I started with there is very little return on investment on writing these sort of tests if your project isn't thousands of developers since the issues with stuff like npm run dev are noticed very very quickly by developers and the cost of having another call-site for them that needs to be aware of certain implementation details is high.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM