babel-plugin-test-doubler.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. /*
  3. A Babel plugin that causes each AVA test to be duplicated with a new title.
  4. test('foo', t => {});
  5. becomes
  6. test('foo', t => {});
  7. test('repeated test: foo', t => {});
  8. This is used by some integration tests to validate correct handling of Babel config options.
  9. */
  10. /* eslint-disable new-cap */
  11. module.exports = babel => {
  12. const t = babel.types;
  13. let anonCount = 1;
  14. return {
  15. visitor: {
  16. CallExpression: path => {
  17. const node = path.node;
  18. const callee = node.callee;
  19. let args = node.arguments;
  20. if (callee.type === 'Identifier' && callee.name === 'test') {
  21. if (args.length === 1) {
  22. args = [t.StringLiteral(`repeated test: anonymous${anonCount++}`), args[0]];
  23. } else if (args.length === 2 && args[0].type === 'StringLiteral') {
  24. if (args[0].value.startsWith('repeated test')) {
  25. return;
  26. }
  27. args = args.slice();
  28. args[0] = t.StringLiteral(`repeated test: ${args[0].value}`);
  29. } else {
  30. throw new Error('The plugin does not know how to handle this call to test');
  31. }
  32. path.insertAfter(t.CallExpression(
  33. t.Identifier('test'),
  34. args
  35. ));
  36. }
  37. }
  38. }
  39. };
  40. };