-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
88 lines (71 loc) · 2.41 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const getAttributeIdentifiers = options => {
if(!options || typeof(options.attributes) === 'undefined') return ['data-test-id', 'data-testid'];
if(Array.isArray(options.attributes)) {
if(options.attributes.length === 0) {
throw new Error('option attributes must be an array with at least one element');
}
if (options.attributes.length !== options.attributes.filter(attr => attr && typeof(attr) === 'string').length) {
throw new Error('all items in the option attributes must be non empty strings');
}
return options.attributes;
}
if(!options.attributes || typeof(options.attributes) !== 'string') {
throw new Error('option attributes must be a non empty string or an array with non empty strings');
}
return [options.attributes];
}
const RemoveDataTestIds = ({ types: t }) => {
const visitor = {
ObjectProperty: (path, state) => {
const attributeIdentifiers = getAttributeIdentifiers(state.opts);
const isTestIdProperty = (key) => {
return attributeIdentifiers.find((attribute) => {
return t.isStringLiteral(key, { value: attribute })
});
};
if (isTestIdProperty(path.node.key))
path.remove();
},
JSXOpeningElement: (path, state) => {
if (path.node.hasStripped) {
return;
}
const attributeIdentifiers = getAttributeIdentifiers(state.opts);
const validTestIdAttributes = attr => {
const isIdent = attributeIdentifiers.find(
attribute => {
return t.isJSXIdentifier(attr.name, { name: attribute });
}
);
return t.isJSXAttribute(attr) && isIdent;
};
const replaceClassNameValues = attr => {
const matchingAttrs = currentAttr => {
if (attr !== currentAttr) {
return currentAttr;
}
};
const isDefined = value => typeof value !== 'undefined';
const attrs = (
path.node.attributes
.map(matchingAttrs)
.filter(isDefined)
);
const node = t.jSXOpeningElement(
path.node.name,
attrs,
path.node.selfClosing
);
node.hasStripped = true;
path.replaceWith(node);
};
path.node.attributes
.filter(validTestIdAttributes)
.forEach(replaceClassNameValues);
}
};
return {
visitor
};
};
export default RemoveDataTestIds;