cli.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. 'use strict';
  2. const fs = require('fs');
  3. const path = require('path');
  4. const childProcess = require('child_process');
  5. const test = require('tap').test;
  6. const getStream = require('get-stream');
  7. const figures = require('figures');
  8. const makeDir = require('make-dir');
  9. const touch = require('touch');
  10. const uniqueTempDir = require('unique-temp-dir');
  11. const execa = require('execa');
  12. const stripAnsi = require('strip-ansi');
  13. const cliPath = path.join(__dirname, '../cli.js');
  14. function execCli(args, opts, cb) {
  15. let dirname;
  16. let env;
  17. if (typeof opts === 'function') {
  18. cb = opts;
  19. dirname = __dirname;
  20. env = {};
  21. } else {
  22. dirname = path.join(__dirname, opts.dirname ? opts.dirname : '');
  23. env = opts.env || {};
  24. }
  25. let child;
  26. let stdout;
  27. let stderr;
  28. const processPromise = new Promise(resolve => {
  29. child = childProcess.spawn(process.execPath, [cliPath].concat(args), {
  30. cwd: dirname,
  31. env: Object.assign({CI: '1'}, env), // Force CI to ensure the correct reporter is selected
  32. // env,
  33. stdio: [null, 'pipe', 'pipe']
  34. });
  35. child.on('close', (code, signal) => {
  36. if (code) {
  37. const err = new Error(`test-worker exited with a non-zero exit code: ${code}`);
  38. err.code = code;
  39. err.signal = signal;
  40. resolve(err);
  41. return;
  42. }
  43. resolve(code);
  44. });
  45. stdout = getStream(child.stdout);
  46. stderr = getStream(child.stderr);
  47. });
  48. Promise.all([processPromise, stdout, stderr]).then(args => {
  49. cb.apply(null, args);
  50. });
  51. return child;
  52. }
  53. for (const which of [
  54. 'bad-key',
  55. 'bad-shortcut',
  56. 'array-test-options',
  57. 'false-test-options',
  58. 'null-test-options',
  59. 'null-extensions',
  60. 'obj-extensions',
  61. 'string-extensions',
  62. 'non-string-value-extensions',
  63. 'empty-string-value-extensions'
  64. ]) {
  65. test(`validates babel config: ${which}`, t => {
  66. execCli(['es2015.js'], {dirname: `fixture/invalid-babel-config/${which}`}, (err, stdout, stderr) => {
  67. t.ok(err);
  68. let expectedOutput = '\n';
  69. expectedOutput += figures.cross + ' Unexpected Babel configuration for AVA.';
  70. expectedOutput += ' See https://github.com/avajs/ava/blob/master/docs/recipes/babel.md for allowed values.';
  71. expectedOutput += '\n';
  72. t.is(stderr, expectedOutput);
  73. t.end();
  74. });
  75. });
  76. }
  77. test('errors if top-level extensions include "js" without babel=false', t => {
  78. execCli(['es2015.js'], {dirname: `fixture/invalid-extensions/top-level`}, (err, stdout, stderr) => {
  79. t.ok(err);
  80. let expectedOutput = '\n';
  81. expectedOutput += figures.cross + ' Cannot specify generic \'js\' extension without disabling AVA\'s Babel usage.';
  82. expectedOutput += '\n';
  83. t.is(stderr, expectedOutput);
  84. t.end();
  85. });
  86. });
  87. for (const [where, which, msg = '\'js\', \'jsx\''] of [
  88. ['top-level', 'top-level-duplicates'],
  89. ['babel', 'babel-duplicates'],
  90. ['top-level and babel', 'shared-duplicates', '\'jsx\'']
  91. ]) {
  92. test(`errors if ${where} extensions include duplicates`, t => {
  93. execCli(['es2015.js'], {dirname: `fixture/invalid-extensions/${which}`}, (err, stdout, stderr) => {
  94. t.ok(err);
  95. let expectedOutput = '\n';
  96. expectedOutput += figures.cross + ` Unexpected duplicate extensions in options: ${msg}.`;
  97. expectedOutput += '\n';
  98. t.is(stderr, expectedOutput);
  99. t.end();
  100. });
  101. });
  102. }
  103. test('formats errors from ava.config.js', t => {
  104. execCli(['es2015.js'], {dirname: 'fixture/load-config/throws'}, (err, stdout, stderr) => {
  105. t.ok(err);
  106. const lines = stderr.split('\n');
  107. t.is(lines[0], '');
  108. t.is(lines[1], figures.cross + ' Error loading ava.config.js');
  109. t.is(lines[2], '');
  110. t.match(lines[3], /ava\.config\.js/);
  111. t.match(lines[4], /foo/);
  112. t.end();
  113. });
  114. });
  115. test('enabling long stack traces will provide detailed debug information', t => {
  116. execCli('fixture/long-stack-trace', (err, stdout, stderr) => {
  117. t.ok(err);
  118. t.match(stderr, /From previous event/);
  119. t.end();
  120. });
  121. });
  122. test('`AssertionError` should capture infinity stack trace', t => {
  123. execCli('fixture/infinity-stack-trace.js', (err, stdout) => {
  124. t.ok(err);
  125. t.match(stdout, /c \(.+?infinity-stack-trace\.js:6:20\)/);
  126. t.match(stdout, /b \(.+?infinity-stack-trace\.js:7:18\)/);
  127. t.match(stdout, /a \(.+?infinity-stack-trace\.js:8:18\)/);
  128. t.end();
  129. });
  130. });
  131. test('timeout', t => {
  132. execCli(['fixture/long-running.js', '-T', '1s'], (err, stdout) => {
  133. t.ok(err);
  134. t.match(stdout, /Exited because no new tests completed within the last 1000ms of inactivity/);
  135. t.end();
  136. });
  137. });
  138. test('include anonymous functions in error reports', t => {
  139. execCli('fixture/error-in-anonymous-function.js', (err, stdout) => {
  140. t.ok(err);
  141. t.match(stdout, /test\/fixture\/error-in-anonymous-function\.js:4:8/);
  142. t.end();
  143. });
  144. });
  145. test('improper use of t.throws will be reported to the console', t => {
  146. execCli('fixture/improper-t-throws/throws.js', (err, stdout) => {
  147. t.ok(err);
  148. t.match(stdout, /Improper usage of `t\.throws\(\)` detected/);
  149. t.match(stdout, /should be detected/);
  150. t.match(stdout, /Try wrapping the first argument/);
  151. t.end();
  152. });
  153. });
  154. test('improper use of t.throws from within a Promise will be reported to the console', t => {
  155. execCli('fixture/improper-t-throws/promise.js', (err, stdout) => {
  156. t.ok(err);
  157. t.match(stdout, /Improper usage of `t\.throws\(\)` detected/);
  158. t.match(stdout, /should be detected/);
  159. t.match(stdout, /Try wrapping the first argument/);
  160. t.end();
  161. });
  162. });
  163. test('improper use of t.throws from within a pending promise, even if caught and rethrown immediately, will be reported to the console', t => {
  164. execCli('fixture/improper-t-throws/leaked-from-promise.js', (err, stdout) => {
  165. t.ok(err);
  166. t.match(stdout, /Improper usage of `t\.throws\(\)` detected/);
  167. t.match(stdout, /should be detected/);
  168. t.match(stdout, /Try wrapping the first argument/);
  169. t.end();
  170. });
  171. });
  172. test('improper use of t.throws from within an async callback will be reported to the console', t => {
  173. execCli('fixture/improper-t-throws/async-callback.js', (err, stdout) => {
  174. t.ok(err);
  175. t.match(stdout, /Improper usage of `t\.throws\(\)` detected/);
  176. t.match(stdout, /should be detected/);
  177. t.match(stdout, /Try wrapping the first argument/);
  178. t.end();
  179. });
  180. });
  181. test('improper use of t.throws, swallowed as an unhandled rejection, will be reported to the console', t => {
  182. execCli('fixture/improper-t-throws/unhandled-rejection.js', (err, stdout) => {
  183. t.ok(err);
  184. t.match(stdout, /Improper usage of `t\.throws\(\)` detected/);
  185. t.match(stdout, /should be detected/);
  186. t.match(stdout, /Try wrapping the first argument/);
  187. t.end();
  188. });
  189. });
  190. test('improper use of t.throws, even if caught, will be reported to the console', t => {
  191. execCli('fixture/improper-t-throws/caught.js', (err, stdout) => {
  192. t.ok(err);
  193. t.match(stdout, /Improper usage of `t\.throws\(\)` detected/);
  194. t.notMatch(stdout, /should be detected/);
  195. t.match(stdout, /Try wrapping the first argument/);
  196. t.end();
  197. });
  198. });
  199. test('improper use of t.throws, even if caught and then rethrown immediately, will be reported to the console', t => {
  200. execCli('fixture/improper-t-throws/caught-and-leaked.js', (err, stdout) => {
  201. t.ok(err);
  202. t.match(stdout, /Improper usage of `t\.throws\(\)` detected/);
  203. t.match(stdout, /should be detected/);
  204. t.match(stdout, /Try wrapping the first argument/);
  205. t.end();
  206. });
  207. });
  208. test('improper use of t.throws, even if caught and then later rethrown, will be reported to the console', t => {
  209. execCli('fixture/improper-t-throws/caught-and-leaked-slowly.js', (err, stdout) => {
  210. t.ok(err);
  211. t.match(stdout, /Improper usage of `t\.throws\(\)` detected/);
  212. t.match(stdout, /should be detected/);
  213. t.match(stdout, /Try wrapping the first argument/);
  214. t.end();
  215. });
  216. });
  217. test('improper use of t.throws, even if caught and then rethrown too slowly, will be reported to the console', t => {
  218. execCli('fixture/improper-t-throws/caught-and-leaked-too-slowly.js', (err, stdout) => {
  219. t.ok(err);
  220. t.match(stdout, /Improper usage of `t\.throws\(\)` detected/);
  221. t.notMatch(stdout, /should be detected/);
  222. t.match(stdout, /Try wrapping the first argument/);
  223. t.end();
  224. });
  225. });
  226. test('precompiler require hook does not apply to source files', t => {
  227. t.plan(3);
  228. execCli('fixture/babel-hook.js', (err, stdout) => {
  229. t.ok(err);
  230. t.is(err.code, 1);
  231. t.match(stdout, /Unexpected (token|reserved word)/);
  232. t.end();
  233. });
  234. });
  235. test('pkg-conf(resolve-dir): works as expected when run from the package.json directory', t => {
  236. execCli(['--verbose'], {dirname: 'fixture/pkg-conf/resolve-dir'}, (err, stdout) => {
  237. t.ifError(err);
  238. t.match(stdout, /dir-a-base-1/);
  239. t.match(stdout, /dir-a-base-2/);
  240. t.notMatch(stdout, /dir-a-wrapper/);
  241. t.notMatch(stdout, /dir-a-wrapper/);
  242. t.end();
  243. });
  244. });
  245. test('pkg-conf(resolve-dir): resolves tests from the package.json dir if none are specified on cli', t => {
  246. execCli(['--verbose'], {dirname: 'fixture/pkg-conf/resolve-dir/dir-a-wrapper'}, (err, stdout) => {
  247. t.ifError(err);
  248. t.match(stdout, /dir-a-base-1/);
  249. t.match(stdout, /dir-a-base-2/);
  250. t.notMatch(stdout, /dir-a-wrapper/);
  251. t.notMatch(stdout, /dir-a-wrapper/);
  252. t.end();
  253. });
  254. });
  255. test('pkg-conf(resolve-dir): resolves tests process.cwd() if globs are passed on the command line', t => {
  256. execCli(['--verbose', 'dir-a/*.js'], {dirname: 'fixture/pkg-conf/resolve-dir/dir-a-wrapper'}, (err, stdout) => {
  257. t.ifError(err);
  258. t.match(stdout, /dir-a-wrapper-3/);
  259. t.match(stdout, /dir-a-wrapper-4/);
  260. t.notMatch(stdout, /dir-a-base/);
  261. t.notMatch(stdout, /dir-a-base/);
  262. t.end();
  263. });
  264. });
  265. test('watcher reruns test files when they changed', t => {
  266. let killed = false;
  267. const child = execCli(['--verbose', '--watch', 'test.js'], {dirname: 'fixture/watcher', env: {CI: ''}}, err => {
  268. t.ok(killed);
  269. t.ifError(err);
  270. t.end();
  271. });
  272. let buffer = '';
  273. let passedFirst = false;
  274. child.stdout.on('data', str => {
  275. buffer += str;
  276. if (/1 test passed/.test(buffer)) {
  277. if (!passedFirst) {
  278. touch.sync(path.join(__dirname, 'fixture/watcher/test.js'));
  279. buffer = '';
  280. passedFirst = true;
  281. } else if (!killed) {
  282. child.kill();
  283. killed = true;
  284. }
  285. }
  286. });
  287. });
  288. test('watcher reruns test files when source dependencies change', t => {
  289. let killed = false;
  290. const child = execCli(['--verbose', '--watch', 'test-*.js'], {dirname: 'fixture/watcher/with-dependencies', env: {CI: ''}}, err => {
  291. t.ok(killed);
  292. t.ifError(err);
  293. t.end();
  294. });
  295. let buffer = '';
  296. let passedFirst = false;
  297. child.stdout.on('data', str => {
  298. buffer += str;
  299. if (/2 tests passed/.test(buffer) && !passedFirst) {
  300. touch.sync(path.join(__dirname, 'fixture/watcher/with-dependencies/source.js'));
  301. buffer = '';
  302. passedFirst = true;
  303. } else if (/1 test passed/.test(buffer) && !killed) {
  304. child.kill();
  305. killed = true;
  306. }
  307. });
  308. });
  309. test('watcher does not rerun test files when they write snapshot files', t => {
  310. let killed = false;
  311. const child = execCli(['--verbose', '--watch', '--update-snapshots', 'test.js'], {dirname: 'fixture/snapshots', env: {CI: ''}}, err => {
  312. t.ok(killed);
  313. t.ifError(err);
  314. t.end();
  315. });
  316. let buffer = '';
  317. let passedFirst = false;
  318. child.stdout.on('data', str => {
  319. buffer += str;
  320. if (/2 tests passed/.test(buffer) && !passedFirst) {
  321. buffer = '';
  322. passedFirst = true;
  323. setTimeout(() => {
  324. child.kill();
  325. killed = true;
  326. }, 500);
  327. } else if (passedFirst && !killed) {
  328. t.is(buffer.replace(/\s/g, ''), '');
  329. }
  330. });
  331. });
  332. test('watcher reruns test files when snapshot dependencies change', t => {
  333. let killed = false;
  334. const child = execCli(['--verbose', '--watch', '--update-snapshots', 'test.js'], {dirname: 'fixture/snapshots', env: {CI: ''}}, err => {
  335. t.ok(killed);
  336. t.ifError(err);
  337. t.end();
  338. });
  339. let buffer = '';
  340. let passedFirst = false;
  341. child.stdout.on('data', str => {
  342. buffer += str;
  343. if (/2 tests passed/.test(buffer)) {
  344. buffer = '';
  345. if (passedFirst) {
  346. child.kill();
  347. killed = true;
  348. } else {
  349. passedFirst = true;
  350. setTimeout(() => {
  351. touch.sync(path.join(__dirname, 'fixture/snapshots/test.js.snap'));
  352. }, 500);
  353. }
  354. }
  355. });
  356. });
  357. test('`"tap": true` config is ignored when --watch is given', t => {
  358. let killed = false;
  359. const child = execCli(['--watch', '--verbose', 'test.js'], {dirname: 'fixture/watcher/tap-in-conf', env: {CI: ''}}, () => {
  360. t.ok(killed);
  361. t.end();
  362. });
  363. let combined = '';
  364. const testOutput = output => {
  365. combined += output;
  366. t.notMatch(combined, /TAP/);
  367. if (/works/.test(combined)) {
  368. child.kill();
  369. killed = true;
  370. }
  371. };
  372. child.stdout.on('data', testOutput);
  373. child.stderr.on('data', testOutput);
  374. });
  375. ['--watch', '-w'].forEach(watchFlag => {
  376. ['--tap', '-t'].forEach(tapFlag => {
  377. test(`bails when ${tapFlag} reporter is used while ${watchFlag} is given`, t => {
  378. execCli([tapFlag, watchFlag, 'test.js'], {dirname: 'fixture/watcher', env: {CI: ''}}, (err, stdout, stderr) => {
  379. t.is(err.code, 1);
  380. t.match(stderr, 'The TAP reporter is not available when using watch mode.');
  381. t.end();
  382. });
  383. });
  384. });
  385. });
  386. ['--watch', '-w'].forEach(watchFlag => {
  387. test(`bails when CI is used while ${watchFlag} is given`, t => {
  388. execCli([watchFlag, 'test.js'], {dirname: 'fixture/watcher', env: {CI: true}}, (err, stdout, stderr) => {
  389. t.is(err.code, 1);
  390. t.match(stderr, 'Watch mode is not available in CI, as it prevents AVA from terminating.');
  391. t.end();
  392. });
  393. });
  394. });
  395. ['--concurrency', '-c'].forEach(concurrencyFlag => {
  396. test(`bails when ${concurrencyFlag} is provided without value`, t => {
  397. execCli(['test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
  398. t.is(err.code, 1);
  399. t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
  400. t.end();
  401. });
  402. });
  403. });
  404. ['--concurrency', '-c'].forEach(concurrencyFlag => {
  405. test(`bails when ${concurrencyFlag} is provided with an input that is a string`, t => {
  406. execCli([`${concurrencyFlag}=foo`, 'test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
  407. t.is(err.code, 1);
  408. t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
  409. t.end();
  410. });
  411. });
  412. });
  413. ['--concurrency', '-c'].forEach(concurrencyFlag => {
  414. test(`bails when ${concurrencyFlag} is provided with an input that is a float`, t => {
  415. execCli([`${concurrencyFlag}=4.7`, 'test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
  416. t.is(err.code, 1);
  417. t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
  418. t.end();
  419. });
  420. });
  421. });
  422. ['--concurrency', '-c'].forEach(concurrencyFlag => {
  423. test(`bails when ${concurrencyFlag} is provided with an input that is negative`, t => {
  424. execCli([`${concurrencyFlag}=-1`, 'test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
  425. t.is(err.code, 1);
  426. t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
  427. t.end();
  428. });
  429. });
  430. });
  431. ['--concurrency', '-c'].forEach(concurrencyFlag => {
  432. test(`works when ${concurrencyFlag} is provided with a value`, t => {
  433. execCli([`${concurrencyFlag}=1`, 'test.js'], {dirname: 'fixture/concurrency'}, err => {
  434. t.ifError(err);
  435. t.end();
  436. });
  437. });
  438. });
  439. test('--match works', t => {
  440. execCli(['-m=foo', '-m=bar', '-m=!baz', '-m=t* a* f*', '-m=!t* a* n* f*', 'fixture/matcher-skip.js'], err => {
  441. t.ifError(err);
  442. t.end();
  443. });
  444. });
  445. ['--tap', '-t'].forEach(tapFlag => {
  446. test(`${tapFlag} should produce TAP output`, t => {
  447. execCli([tapFlag, 'test.js'], {dirname: 'fixture/watcher'}, err => {
  448. t.ok(!err);
  449. t.end();
  450. });
  451. });
  452. });
  453. test('handles NODE_PATH', t => {
  454. const nodePaths = `fixture/node-paths/modules${path.delimiter}fixture/node-paths/deep/nested`;
  455. execCli('fixture/node-paths.js', {env: {NODE_PATH: nodePaths}}, err => {
  456. t.ifError(err);
  457. t.end();
  458. });
  459. });
  460. test('works when no files are found', t => {
  461. execCli('!*', (err, stdout) => {
  462. t.is(err.code, 1);
  463. t.match(stdout, 'Couldn\'t find any files to test');
  464. t.end();
  465. });
  466. });
  467. test('should warn ava is required without the cli', t => {
  468. childProcess.execFile(process.execPath, [path.resolve(__dirname, '../index.js')], error => {
  469. t.ok(error);
  470. t.match(error.message, /Test files must be run with the AVA CLI/);
  471. t.end();
  472. });
  473. });
  474. test('prefers local version of ava', t => {
  475. execCli('', {
  476. dirname: 'fixture/local-bin',
  477. env: {
  478. DEBUG: 'ava'
  479. }
  480. }, (err, stdout, stderr) => {
  481. t.ifError(err);
  482. t.match(stderr, 'Using local install of AVA');
  483. t.end();
  484. });
  485. });
  486. test('use current working directory if `package.json` is not found', () => {
  487. const cwd = uniqueTempDir({create: true});
  488. const testFilePath = path.join(cwd, 'test.js');
  489. const cliPath = require.resolve('../cli.js');
  490. const avaPath = require.resolve('../');
  491. fs.writeFileSync(testFilePath, `import test from ${JSON.stringify(avaPath)};\ntest('test', t => { t.pass(); });`);
  492. return execa(process.execPath, [cliPath], {cwd, env: {CI: '1'}});
  493. });
  494. test('workers ensure test files load the same version of ava', t => {
  495. const target = path.join(__dirname, 'fixture', 'ava-paths', 'target');
  496. // Copy the index.js so the testFile imports it. It should then load the correct AVA install.
  497. const targetInstall = path.join(target, 'node_modules/ava');
  498. makeDir.sync(targetInstall);
  499. fs.writeFileSync(
  500. path.join(targetInstall, 'index.js'),
  501. fs.readFileSync(path.join(__dirname, '../index.js'))
  502. );
  503. const testFile = path.join(target, 'test.js');
  504. execCli([testFile], {dirname: path.join('fixture', 'ava-paths', 'cwd')}, err => {
  505. t.ifError(err);
  506. t.end();
  507. });
  508. });
  509. test('tests without assertions do not fail if failWithoutAssertions option is set to false', t => {
  510. execCli([], {dirname: 'fixture/pkg-conf/fail-without-assertions'}, err => {
  511. t.ifError(err);
  512. t.end();
  513. });
  514. });
  515. test('callback tests fail if event loop empties before they\'re ended', t => {
  516. execCli('callback.js', {dirname: 'fixture/stalled-tests'}, (_, stdout) => {
  517. t.match(stdout, /`t\.end\(\)` was never called/);
  518. t.end();
  519. });
  520. });
  521. test('observable tests fail if event loop empties before they\'re resolved', t => {
  522. execCli('observable.js', {dirname: 'fixture/stalled-tests'}, (_, stdout) => {
  523. t.match(stdout, /Observable returned by test never completed/);
  524. t.end();
  525. });
  526. });
  527. test('promise tests fail if event loop empties before they\'re resolved', t => {
  528. execCli('promise.js', {dirname: 'fixture/stalled-tests'}, (_, stdout) => {
  529. t.match(stdout, /Promise returned by test never resolved/);
  530. t.end();
  531. });
  532. });
  533. for (const obj of [
  534. {type: 'colocated', rel: '', dir: ''},
  535. {type: '__tests__', rel: '__tests__-dir', dir: '__tests__/__snapshots__'},
  536. {type: 'test', rel: 'test-dir', dir: 'test/snapshots'},
  537. {type: 'tests', rel: 'tests-dir', dir: 'tests/snapshots'}
  538. ]) {
  539. test(`snapshots work (${obj.type})`, t => {
  540. const snapPath = path.join(__dirname, 'fixture', 'snapshots', obj.rel, obj.dir, 'test.js.snap');
  541. try {
  542. fs.unlinkSync(snapPath);
  543. } catch (err) {
  544. if (err.code !== 'ENOENT') {
  545. throw err;
  546. }
  547. }
  548. const dirname = path.join('fixture/snapshots', obj.rel);
  549. // Test should pass, and a snapshot gets written
  550. execCli(['--update-snapshots'], {dirname}, err => {
  551. t.ifError(err);
  552. t.true(fs.existsSync(snapPath));
  553. // Test should pass, and the snapshot gets used
  554. execCli([], {dirname}, err => {
  555. t.ifError(err);
  556. t.end();
  557. });
  558. });
  559. });
  560. }
  561. test('appends to existing snapshots', t => {
  562. const cliPath = require.resolve('../cli.js');
  563. const avaPath = require.resolve('../');
  564. const cwd = uniqueTempDir({create: true});
  565. fs.writeFileSync(path.join(cwd, 'package.json'), '{}');
  566. const initial = `import test from ${JSON.stringify(avaPath)}
  567. test('one', t => {
  568. t.snapshot({one: true})
  569. })`;
  570. fs.writeFileSync(path.join(cwd, 'test.js'), initial);
  571. const run = () => execa(process.execPath, [cliPath, '--verbose', '--no-color'], {cwd, env: {CI: '1'}, reject: false});
  572. return run().then(result => {
  573. t.match(result.stdout, /1 test passed/);
  574. fs.writeFileSync(path.join(cwd, 'test.js'), `${initial}
  575. test('two', t => {
  576. t.snapshot({two: true})
  577. })`);
  578. return run();
  579. }).then(result => {
  580. t.match(result.stdout, /2 tests passed/);
  581. fs.writeFileSync(path.join(cwd, 'test.js'), `${initial}
  582. test('two', t => {
  583. t.snapshot({two: false})
  584. })`);
  585. return run();
  586. }).then(result => {
  587. t.match(result.stdout, /1 test failed/);
  588. });
  589. });
  590. test('outdated snapshot version is reported to the console', t => {
  591. const snapPath = path.join(__dirname, 'fixture', 'snapshots', 'test.js.snap');
  592. fs.writeFileSync(snapPath, Buffer.from([0x0A, 0x00, 0x00]));
  593. execCli(['test.js'], {dirname: 'fixture/snapshots'}, (err, stdout) => {
  594. t.ok(err);
  595. t.match(stdout, /The snapshot file is v0, but only v1 is supported\./);
  596. t.match(stdout, /File path:/);
  597. t.match(stdout, snapPath);
  598. t.match(stdout, /Please run AVA again with the .*--update-snapshots.* flag to upgrade\./);
  599. t.end();
  600. });
  601. });
  602. test('newer snapshot version is reported to the console', t => {
  603. const snapPath = path.join(__dirname, 'fixture', 'snapshots', 'test.js.snap');
  604. fs.writeFileSync(snapPath, Buffer.from([0x0A, 0xFF, 0xFF]));
  605. execCli(['test.js'], {dirname: 'fixture/snapshots'}, (err, stdout) => {
  606. t.ok(err);
  607. t.match(stdout, /The snapshot file is v65535, but only v1 is supported\./);
  608. t.match(stdout, /File path:/);
  609. t.match(stdout, snapPath);
  610. t.match(stdout, /You should upgrade AVA\./);
  611. t.end();
  612. });
  613. });
  614. test('snapshot corruption is reported to the console', t => {
  615. const snapPath = path.join(__dirname, 'fixture', 'snapshots', 'test.js.snap');
  616. fs.writeFileSync(snapPath, Buffer.from([0x0A, 0x01, 0x00]));
  617. execCli(['test.js'], {dirname: 'fixture/snapshots'}, (err, stdout) => {
  618. t.ok(err);
  619. t.match(stdout, /The snapshot file is corrupted\./);
  620. t.match(stdout, /File path:/);
  621. t.match(stdout, snapPath);
  622. t.match(stdout, /Please run AVA again with the .*--update-snapshots.* flag to recreate it\./);
  623. t.end();
  624. });
  625. });
  626. test('legacy snapshot files are reported to the console', t => {
  627. const snapPath = path.join(__dirname, 'fixture', 'snapshots', 'test.js.snap');
  628. fs.writeFileSync(snapPath, Buffer.from('// Jest Snapshot v1, https://goo.gl/fbAQLP\n'));
  629. execCli(['test.js'], {dirname: 'fixture/snapshots'}, (err, stdout) => {
  630. t.ok(err);
  631. t.match(stdout, /The snapshot file was created with AVA 0\.19\. It's not supported by this AVA version\./);
  632. t.match(stdout, /File path:/);
  633. t.match(stdout, snapPath);
  634. t.match(stdout, /Please run AVA again with the .*--update-snapshots.* flag to upgrade\./);
  635. t.end();
  636. });
  637. });
  638. test('snapshots infer their location from sourcemaps', t => {
  639. t.plan(8);
  640. const relativeFixtureDir = path.join('fixture/snapshots/test-sourcemaps');
  641. const snapDirStructure = [
  642. 'src',
  643. 'src/test/snapshots',
  644. 'src/feature/__tests__/__snapshots__'
  645. ];
  646. const snapFixtureFilePaths = snapDirStructure
  647. .map(snapRelativeDir => {
  648. const snapPath = path.join(__dirname, relativeFixtureDir, snapRelativeDir);
  649. return [
  650. path.join(snapPath, 'test.js.md'),
  651. path.join(snapPath, 'test.js.snap')
  652. ];
  653. })
  654. .reduce((a, b) => a.concat(b), []);
  655. const removeExistingSnapFixtureFiles = snapPath => {
  656. try {
  657. fs.unlinkSync(snapPath);
  658. } catch (err) {
  659. if (err.code !== 'ENOENT') {
  660. throw err;
  661. }
  662. }
  663. };
  664. snapFixtureFilePaths.forEach(x => removeExistingSnapFixtureFiles(x));
  665. const verifySnapFixtureFiles = relFilePath => {
  666. t.true(fs.existsSync(relFilePath));
  667. };
  668. execCli([], {dirname: relativeFixtureDir}, (err, stdout) => {
  669. t.ifError(err);
  670. snapFixtureFilePaths.forEach(x => verifySnapFixtureFiles(x));
  671. t.match(stdout, /6 tests passed/);
  672. t.end();
  673. });
  674. });
  675. test('snapshots resolved location from "snapshotDir" in AVA config', t => {
  676. t.plan(8);
  677. const relativeFixtureDir = 'fixture/snapshots/test-snapshot-location';
  678. const snapDir = 'snapshot-fixtures';
  679. const snapDirStructure = [
  680. 'src',
  681. 'src/feature',
  682. 'src/feature/nested-feature'
  683. ];
  684. const snapFixtureFilePaths = snapDirStructure
  685. .map(snapRelativeDir => {
  686. const snapPath = path.join(__dirname, relativeFixtureDir, snapDir, snapRelativeDir);
  687. return [
  688. path.join(snapPath, 'test.js.md'),
  689. path.join(snapPath, 'test.js.snap')
  690. ];
  691. })
  692. .reduce((a, b) => a.concat(b), []);
  693. const removeExistingSnapFixtureFiles = snapPath => {
  694. try {
  695. fs.unlinkSync(snapPath);
  696. } catch (err) {
  697. if (err.code !== 'ENOENT') {
  698. throw err;
  699. }
  700. }
  701. };
  702. snapFixtureFilePaths.forEach(x => removeExistingSnapFixtureFiles(x));
  703. const verifySnapFixtureFiles = relFilePath => {
  704. t.true(fs.existsSync(relFilePath));
  705. };
  706. execCli([], {dirname: relativeFixtureDir}, (err, stdout) => {
  707. t.ifError(err);
  708. snapFixtureFilePaths.forEach(x => verifySnapFixtureFiles(x));
  709. t.match(stdout, /6 tests passed/);
  710. t.end();
  711. });
  712. });
  713. test('--no-color disables formatting colors', t => {
  714. execCli(['--no-color', '--verbose', 'formatting-color.js'], {dirname: 'fixture'}, (err, stdout) => {
  715. t.ok(err);
  716. t.is(stripAnsi(stdout), stdout);
  717. t.end();
  718. });
  719. });
  720. test('--color enables formatting colors', t => {
  721. execCli(['--color', '--verbose', 'formatting-color.js'], {dirname: 'fixture'}, (err, stdout) => {
  722. t.ok(err);
  723. t.isNot(stripAnsi(stdout), stdout);
  724. t.end();
  725. });
  726. });
  727. test('sets NODE_ENV to test when it is not set', t => {
  728. execCli([path.join('fixture', 'node-env-test.js')], {env: {}}, (err, stdout) => {
  729. t.ifError(err);
  730. t.match(stdout, /1 test passed/);
  731. t.end();
  732. });
  733. });
  734. test('doesn\'t set NODE_ENV when it is set', t => {
  735. execCli([path.join('fixture', 'node-env-foo.js')], {env: {NODE_ENV: 'foo'}}, (err, stdout) => {
  736. t.ifError(err);
  737. t.match(stdout, /1 test passed/);
  738. t.end();
  739. });
  740. });
  741. test('skips test file compilation when babel=false and compileEnhancements=false', t => {
  742. execCli(['import.js'], {dirname: 'fixture/no-babel-compilation'}, (err, stdout) => {
  743. t.ok(err);
  744. t.match(stdout, /SyntaxError: Unexpected (reserved word|token import|identifier)/);
  745. t.end();
  746. });
  747. });
  748. test('skips helper file compilation when babel=false and compileEnhancements=false', t => {
  749. execCli(['require-helper.js'], {dirname: 'fixture/no-babel-compilation'}, (err, stdout) => {
  750. t.ifError(err);
  751. t.match(stdout, /1 test passed/);
  752. t.end();
  753. });
  754. });
  755. test('no power-assert when babel=false and compileEnhancements=false', t => {
  756. execCli(['no-power-assert.js'], {dirname: 'fixture/no-babel-compilation'}, (err, stdout) => {
  757. t.ok(err);
  758. t.notMatch(stripAnsi(stdout), /bool\n.*=> false/);
  759. t.end();
  760. });
  761. });
  762. test('skips stage-4 transform when babel=false and compileEnhancements=true', t => {
  763. execCli(['import.js'], {dirname: 'fixture/just-enhancement-compilation'}, (err, stdout) => {
  764. t.ok(err);
  765. t.match(stdout, /SyntaxError: Unexpected (reserved word|token import|identifier)/);
  766. t.end();
  767. });
  768. });
  769. test('power-assert when babel=false and compileEnhancements=true', t => {
  770. execCli(['power-assert.js'], {dirname: 'fixture/just-enhancement-compilation'}, (err, stdout) => {
  771. t.ok(err);
  772. t.match(stripAnsi(stdout), /bool\n.*=> false/);
  773. t.end();
  774. });
  775. });
  776. test('power-assert with custom extension and no regular babel pipeline', t => {
  777. execCli(['.'], {dirname: 'fixture/just-enhancement-compilation/custom-extension'}, (err, stdout) => {
  778. t.ok(err);
  779. t.match(stripAnsi(stdout), /bool\n.*=> false/);
  780. t.end();
  781. });
  782. });
  783. test('workers load compiled helpers if in the require configuration', t => {
  784. execCli(['test/verify.js'], {dirname: 'fixture/require-compiled-helper'}, err => {
  785. t.ifError(err);
  786. t.end();
  787. });
  788. });
  789. test('additional arguments are forwarded to the worker', t => {
  790. execCli(['worker-argv.js', '--serial', '--', '--hello', 'world'], {dirname: 'fixture'}, err => {
  791. t.ifError(err);
  792. t.end();
  793. });
  794. });
  795. test('--reset-cache resets cache', t => {
  796. const cacheDir = path.join(__dirname, 'fixture', 'reset-cache', 'node_modules', '.cache', 'ava');
  797. execCli([], {dirname: 'fixture/reset-cache'}, err => {
  798. t.ifError(err);
  799. t.true(fs.readdirSync(cacheDir).length > 0);
  800. execCli(['--reset-cache'], {dirname: 'fixture/reset-cache'}, err => {
  801. t.ifError(err);
  802. t.true(fs.readdirSync(cacheDir).length === 0);
  803. t.end();
  804. });
  805. });
  806. });