Named export arrow function name inference
See original GitHub issueDescription
When a React component is defined as a named export arrow function, the name of it cannot be inferred correctly in jest coverage mode. (To be precise, it’s node that cannot infer it) It generates inconsistent result compared with the stored snapshots.
What’s a named export arrow function?
export const MyFancyComponent = props => <div {...props} />
Digging in
It turns out the above MyFancyComponent
will be transpiled (proper babel-preset-env
) into this:
var MyFancyComponent = exports.MyFancyComponent = (cov_15qdocbbym.s[0]++, props => {
cov_15qdocbbym.f[0]++;
cov_15qdocbbym.s[1]++;
return <div {...props />;
});
where the instrument code is inserted along with the arrow function, generating a SequenceExpression
. However, node
(I’m using 8.2.1
) cannot infer the name of the arrow function inside a sequence expression.
> const a = (1, () => 2);
undefined
> a.name
''
> const b = () => 3;
undefined
> b.name
'b'
A possible solution
Modify the insertCounter
function in istanbul-lib-instrument/src/visitor.js
as follows:
- if (parent && (T.isProgram(parent.parentPath) || T.isBlockStatement(parent.parentPath))) {
+ if (parent && T.isExportNamedDeclaration(parent.parentPath)) {
+ parent.parentPath.insertBefore(T.expressionStatement(increment));
+ } else if (parent && (T.isProgram(parent.parentPath) || T.isBlockStatement(parent.parentPath))) {
Thus, the generated code would be something like:
cov_15qdocbbym.s[0]++;
var foo = exports.foo = props => {
cov_15qdocbbym.f[0]++;
cov_15qdocbbym.s[1]++;
return 'bar';
};
Thus, node
can infer foo now 😃
Questions
- What’s the current policies for ES modules of
istanbul
projects? - Is it a good practice to make such changes for ES modules compatibility?
- Would you accept a PR?
Repos
I put my changes of istanbul-lib-instrument
into my forked repo:
I also published it as a scoped npm module under @tomchentw/istanbul-lib-instrument
, hence I can forked babel-plugin-istanbul
to add a failing case and fix it:
Related issues
#63 ……and maybe more.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:6
- Comments:5 (1 by maintainers)
Top GitHub Comments
That’s because of issues with jest caching; it should be a separate issue.
@jdolle https://github.com/facebook/jest/issues/1740#issuecomment-338863987