简体   繁体   English

npm脚本测试

[英]Testing of npm scripts

How can I write a test that npm scripts run successfully?如何编写 npm 脚本成功运行的测试?

I have npm scripts in package.json as follows.我在package.json中有 npm 脚本,如下所示。

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

I'd like to test these npm scripts launch successfully.我想测试这些 npm 脚本是否成功启动。

For example, how do I test the command npm run dev ( webpack serve ) launches successfully?例如,如何测试命令npm run dev ( webpack serve ) 启动成功?

You test them like you test a computer process - independent of JavaScript.您可以像测试计算机进程一样测试它们——独立于 JavaScript。 You treat the fact webpack/eslint are JavaScript programs as an implementation detail.您将 webpack/eslint 是 JavaScript 程序这一事实视为实现细节。

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.请注意,就像我一开始一样,如果您的项目不是成千上万的开发人员,那么编写此类测试的投资回报率很低,因为开发人员很快就会注意到npm run dev等问题,并且拥有另一个需要了解某些实现细节的呼叫站点很高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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