babel-plugin-espower icon indicating copy to clipboard operation
babel-plugin-espower copied to clipboard

Allow custom matching.

Open jamestalmage opened this issue 7 years ago • 2 comments

See https://github.com/avajs/ava/issues/1031

The issue arises because users don't necessarily want to use t as their variable name.

Instead of just allowing patterns, it seems possible to allow a more complex matching scheme where implementors can actually use the Babel API for matching.

// Example implementation for AVA

const patterns = [
  't.is(actual, expected, [message])',
  't.not(actual, expected, [message])',
  // ...
];

function isAvaTestCall(callExpression) {
  // figure out if this is a call to AVA's `test` function
}

function isAvaImplementation(functionDeclaration) {
  // figure out if this is a valid test implementation (i.e. function declaration, arrow function) 
}

const matcher = {
  CallExpression: function (path, state) {
    const args = path.get('arguments');
    let param;

    if (isAvaTestCall(path)) {
      if (isAvaImplementation(args[0])) {
        // implementation is the first param (no message)
        param = args[0];
      } else if (isAvaImplementation(args[1])) {
        // implementation is the second param (message is the first)
        param = args[1];
      } else {
        return;
      }

      // The register function is provided as a mixin for your matcher.
      // Registration causes the param to be treated as `t` for the purpose of pattern matching, regardless of what it is actually called by the user.
      this.registerInterestAs(param, 't');
    }
  }
};

const plugin = createEspowerPlugin(patterns, matcher);

jamestalmage avatar Sep 02 '16 19:09 jamestalmage