Skip to content

feat: add support for @testing-library/user-event #176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-toastify": "^6.0.5",
"react-toggle": "^4.1.1",
"react-virtualized-auto-sizer": "^1.0.2",
"react-window": "^1.8.5"
},
Expand Down Expand Up @@ -96,7 +97,7 @@
"jest": {
"verbose": true,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|svg)$": "<rootDir>/src/__mocks__/fileMock.js"
"\\.(jpg|jpeg|png|svg|css)$": "<rootDir>/src/__mocks__/fileMock.js"
},
"setupFilesAfterEnv": [
"./tests/setupTests.js"
Expand Down
10 changes: 7 additions & 3 deletions src/components/Playground.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function onStateChange({ markup, query, result }) {
const initialValues = state.load() || {};

function Playground() {
const [{ markup, query, result }, dispatch] = usePlayground({
const [{ markup, query, result, eventExecuted }, dispatch] = usePlayground({
onChange: onStateChange,
...initialValues,
});
Expand All @@ -29,7 +29,7 @@ function Playground() {

<div className="flex-auto h-56 md:h-full">
<Preview
markup={markup}
markup={eventExecuted ? result.markup : markup}
elements={result.elements}
accessibleRoles={result.accessibleRoles}
dispatch={dispatch}
Expand All @@ -45,7 +45,11 @@ function Playground() {
</div>

<div className="flex-auto h-56 md:h-full overflow-hidden">
<Result result={result} dispatch={dispatch} />
<Result
result={result}
eventExecuted={eventExecuted}
dispatch={dispatch}
/>
</div>
</div>
</div>
Expand Down
9 changes: 7 additions & 2 deletions src/components/Result.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@ import ResultQueries from './ResultQueries';
import ResultSuggestion from './ResultSuggestion';
import Scrollable from './Scrollable';
import { emptyResult } from '../lib';
import UserEventResult from './UserEventResult';

function Result({ result, dispatch }) {
function Result({ result, eventExecuted, dispatch }) {
if (result.error) {
return (
<ErrorBox caption={result.error.message} body={result.error.details} />
);
}

if (result.expression && result.expression.userEvent) {
return (
<UserEventResult eventExecuted={eventExecuted} dispatch={dispatch} />
);
}
if (
!result.expression ||
!Array.isArray(result.elements) ||
Expand Down
47 changes: 47 additions & 0 deletions src/components/UserEventResult.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import React from 'react';
import Toggle from 'react-toggle';
import 'react-toggle/style.css';

const UserEventResult = ({ eventExecuted, dispatch }) => {
const handleToggleChange = () =>
dispatch({
type: 'TOGGLE_EXECUTION',
});

const label = eventExecuted
? 'showing the preview after user-event action is applied'
: 'showing the preview according to the original markup';

return (
<div className="flex flex-col h-full">
<div className="min-h-8 space-y-4 text-sm">
<p>
<a
href="https://testing-library.com/docs/ecosystem-user-event"
rel="noopener noreferrer"
target="_blank"
className="font-bold"
>
@testing-library/user-event
</a>{' '}
method detected!
</p>
</div>
<div className="flex-auto flex items-center">
<label className="w-full flex items-center justify-center">
<div className="flex-auto flex justify-center">
<Toggle
onChange={handleToggleChange}
defaultChecked={eventExecuted}
/>
</div>
<span className="min-h-8 space-y-4 text-sm flex-auto flex">
{label}
</span>
</label>
</div>
</div>
);
};

export default UserEventResult;
6 changes: 5 additions & 1 deletion src/hooks/usePlayground.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ function reducer(state, action) {
};
}

case 'TOGGLE_EXECUTION': {
return { ...state, eventExecuted: !state.eventExecuted };
}

default: {
throw new Error('Unknown action type: ' + action.type);
}
Expand All @@ -65,6 +69,7 @@ function usePlayground(props) {
const [state, dispatch] = useReducer(withLogging(reducer), {
rootNode,
markup,
eventExecuted: result ? result.markup !== markup : false,
query,
result,
});
Expand All @@ -74,7 +79,6 @@ function usePlayground(props) {
onChange(state);
}
}, [state.result]);

return [state, dispatch];
}

Expand Down
30 changes: 30 additions & 0 deletions src/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
logDOM,
} from '@testing-library/dom';

import userEvent from '@testing-library/user-event';

const debug = (element, maxLength, options) =>
Array.isArray(element)
? element.map((el) => logDOM(el, maxLength, options)).join('\n')
Expand Down Expand Up @@ -81,13 +83,15 @@ function getLastExpression(code) {
level,
args,
call,
userEvent: minified.trim().startsWith('userEvent.'),
};
}

function createEvaluator({ rootNode }) {
const context = Object.assign({}, queries, {
screen: getScreen(rootNode),
container: rootNode,
userEvent,
});

const evaluator = Function.apply(null, [
Expand All @@ -109,6 +113,7 @@ function createEvaluator({ rootNode }) {
details: error.slice(1).join('\n').trim(),
};
}
result.markup = rootNode.innerHTML;

result.elements = ensureArray(result.data)
.filter((x) => x?.nodeType === Node.ELEMENT_NODE)
Expand Down Expand Up @@ -140,6 +145,19 @@ function createEvaluator({ rootNode }) {
return { context, evaluator, exec, wrap };
}

function parseScripts(markup) {
const container = document.createElement('div');
container.innerHTML = markup;
const scriptsCollections = container.getElementsByTagName('script');
const jsScripts = Array.from(scriptsCollections).filter(
(script) => script.type === 'text/javascript' || script.type === '',
);
return jsScripts.map((script) => ({
scriptCode: script.innerHTML,
evaluated: false,
}));
}

function createSandbox({ markup }) {
// render the frame in a container, so we can set "display: none". If the
// hiding would be done in the frame itself, testing-library would mark the
Expand Down Expand Up @@ -194,6 +212,17 @@ function createSandbox({ markup }) {
body = html;
}
},
evalScripts: () =>
parseScripts(markup)
.filter((script) => !script.evaluated)
.forEach((script) => {
try {
frame.contentWindow.exec(context, script.scriptCode);
script.evaluated = true;
} catch (e) {
console.log(e);
}
}),
eval: (query) =>
wrap(() => frame.contentWindow.exec(context, query), { markup, query }),
destroy: () => document.body.removeChild(container),
Expand All @@ -217,6 +246,7 @@ function runInSandbox({ markup, query, cacheId }) {
const sandbox = sandboxes[cacheId] || createSandbox({ markup });
sandbox.ensureMarkup(markup);

sandbox.evalScripts();
const result = sandbox.eval(query);

if (cacheId && !sandboxes[cacheId]) {
Expand Down