Testing for existence of react-modal using React Testing Library with findByRole - react-testing-library

I am trying to test for the existence of my modal using React Testing Library with findByRole. I keep getting an error saying: Unable to find role="dialog" even though I can see clearly see it printed out in the console of the test.
Here is my test:
import React from "react";
import {
render,
screen,
within,
fireEvent, cleanup, waitFor
} from '#testing-library/react';
import '#testing-library/jest-dom';
import "#testing-library/react/dont-cleanup-after-each";
import Modal from 'react-modal';
import PackagerModal from './PackagerModal';
const mockedEmptyFn = jest.fn();
const mockBaseProps = {
openPackager: true,
setOpenPackager: mockedEmptyFn,
activeOrder: {
// ... // lots of irrelevant properties here
]
},
setOrders: mockedEmptyFn,
customStyles: {
content: {
backgroundColor: "var(--color-primary)",
border: "1px solid #ccc",
boxShadow: "-2rem 2rem 2rem rgba(0, 0, 0, 0.5)",
color: "rgba(var(--RGB-text), 0.8)",
filter: "blur(0)",
fontSize: "1.1em",
fontWeight: "bold",
margin: "50px auto",
opacity: 1,
outline: 0,
position: "relative",
visibility: "visible",
width: "500px"
},
overlay: {
backgroundColor: "rgba(255, 255, 255, 0.9)"
}
},
readOnly: false,
setReadOnly: mockedEmptyFn,
};
Modal.setAppElement('body');
const Component = (props) => <PackagerModal {...mockBaseProps} {...props} />
describe('Packager Modal tests with editable inputs', () => {
afterAll(() => {
cleanup();
});
test('Should show packager modal', async () => {
render(
<Component/>
);
// screen.debug();
const modalWindow = await screen.findByRole('dialog');
expect(modalWindow).toBeInTheDocument();
});
});
And here is my modal:
import ReactModal from 'react-modal';
import React, { useEffect, useRef, useState } from 'react';
import CloseButton from './CloseButton';
import PropTypes from 'prop-types';
const PackagerModal = (props) => {
const {
openPackager,
setOpenPackager,
activeOrder,
setOrders,
customStyles,
readOnly,
setReadOnly,
} = props;
const cleanUpModal = () => {
setReadOnly(false);
setUserInput(initialState);
};
return (
<ReactModal
isOpen={openPackager}
style={customStyles}
className={'order-details-modal'}
closeTimeoutMS={1000}
onAfterClose={cleanUpModal}
>
<CloseButton setOpenModal={setOpenPackager} />
<h2 className={'title'}>Packager Order Checklist</h2>
</ReactModal>
);
};
PackagerModal.propTypes = {
openPackager: PropTypes.bool.isRequired,
setOpenPackager: PropTypes.func.isRequired,
customStyles: PropTypes.object.isRequired,
activeOrder: PropTypes.object.isRequired,
setOrders: PropTypes.func.isRequired,
readOnly: PropTypes.bool.isRequired,
setReadOnly: PropTypes.func.isRequired,
};
export default PackagerModal;
And finally, here is some of the output I see in the console from the test:
● Packager Modal tests with editable inputs › Should show packager modal
Unable to find role="dialog"
Ignored nodes: comments, script, style
<body
aria-hidden="true"
class="ReactModal__Body--open"
>
<div
data-react-modal-body-trap=""
style="position: absolute; opacity: 0;"
tabindex="0"
/>
<div />
<div
data-react-modal-body-trap=""
style="position: absolute; opacity: 0;"
tabindex="0"
/>
<div
class="ReactModalPortal"
>
<div
class="ReactModal__Overlay ReactModal__Overlay--after-open"
style="position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; background-color: rgba(255, 255, 255, 0.9);"
>
<div
aria-modal="true"
class="ReactModal__Content ReactModal__Content--after-open order-details-modal"
role="dialog"
style="border: 1px solid #ccc; box-shadow: -2rem 2rem 2rem rgba(0, 0, 0, 0.5); filter: blur(0); font-size: 1.1em; font-weight: bold; margin: 50px auto; opacity: 1; outline: 0; position: relative; visibility: visible; width: 500px;"
tabindex="-1"
>
...

Looks like the body of your test is set to hidden - aria-hidden="true" (not sure why as I'm not familiar with the package). React Testing Library is heavily accessibility oriented, so by default it ignores any elements that are not accessible.
Try querying your element with the { hidden: true } option
const myModal = getByRole('dialog', { hidden: true });

Though Avi's answer works, it technically isn't the best for testing. I was having the same issue and have realised we also have the same issue with our code so here is what is happening.
The issue is that you are saying Modal.setAppElement('body'); in your test file.
If you read the docs for react-modal, they say you need to tell the modal where your apps content is so that when the modal is open, everything within that element will have aria-hidden: true so that screen readers don't pick up any of the other content other than whats inside the modal since that gets rendered via a portal appended to the end of your body. So you setting setAppElement to body is making everything inside that hidden to screen readers, including your modal.
So to solve this you need to set that to something else, I personally have my own render function that has things like providers so I just added a new div in there. But in your case you could add it to your Component
const Component = (props) => <div id="root"><PackagerModal {...mockBaseProps} {...props} /></div>
Then you can chance the line setAppElement line to
Modal.setAppElement('root');
This will mean that you don't have to add the { hidden: true } option to your queries.
You also dont have to use findBy since there isn't any async changes happening in your test so far
test('Should show packager modal', () => {
render(<Component/>);
const modalWindow = screen.getByRole('dialog');
expect(modalWindow).toBeInTheDocument();
});

Related

Framer Motion ReOrder behaviour not reordering as expected

I am currently trying to implemented a draggable re-orderable list with Framer Motion. I am trying to reproduce the following behaviour:
https://codesandbox.io/s/framer-motion-5-drag-to-reorder-lists-uonye?from-embed=&file=/src/Icon.tsx:49-54
I have an ingredientList that contains the create_index of the each of the ingredients created in my Formik form, which are accessible as values.ingredients.
The main issue I am having is that the list items are not behaving smoothly as they do in the code example and I'm not sure what I am doing wrong
This is my parent component in which I set the ingredientList
const IngredientTab = ({values}: any) => {
const [ingredientList, setIngredientList] = useState(values.ingredients.map((ingredient) => ingredient.create_index))
return (
<div css={IngredientTabStyles}>
<FieldArray name="ingredients">
{({ insert, remove, push }) => (
<div>
<Reorder.Group axis="y" values={ingredientList} onReorder={setIngredientList}>
<AnimatePresence>
{ingredientList.map((ingredientUniqueValue, index) => {
return (
<Ingredient
key={index}
index={index}
uniqueValue={ingredientUniqueValue}
ingredients={values.ingredients}
order={`${ingredientList.indexOf(ingredientUniqueValue) + 1}`}
/>
)
})}
</AnimatePresence>
</Reorder.Group>
<button
type="button"
className="add-ingredients"
onClick={() => {
setIngredientList([...ingredientList, values.ingredients.length])
push({ name: '', additional_info: '', quantity: '', unit_id: '', create_index: values.ingredients.length})
}}
>
Add Ingredient
</button>
</div>
)}
</FieldArray>
</div>
)
}
export default IngredientTab
const IngredientTabStyles = css`
.ingredient-fields {
margin-bottom: 2rem;
background-color: white;
}
`
And this is the Item component:
const Ingredient = ({ uniqueValue, ingredients, order, ingredient}: any) => {
const y = useMotionValue(0);
const boxShadow = useRaisedShadow(y);
const ingredientIndex = ingredients.findIndex(ingredient => ingredient.create_index==uniqueValue)
return (
<Reorder.Item
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
key={uniqueValue}
value={uniqueValue}
style={{boxShadow,y}}
>
{ingredient}
<div className="ingredient-fields" css={IngredientStyles}>
<div className="order">
<h6>{order}</h6>
</div>
<div className="ingredient-name">
<Field
name={`ingredients.${ingredientIndex}.name`}
type='text'
placeholder="Ingredient"
/>
<Field
name={`ingredients.${ingredientIndex}.additional_info`}
type='text'
placeholder="Description"
/>
</div>
<Field
name={`ingredients.${ingredientIndex}.quantity`}
type='number'
placeholder="Quantity"
/>
</div>
</Reorder.Item>
)
}
export default Ingredient
const IngredientStyles = css`
display: flex;
margin-bottom: 2rem;
.order {
display: flex;
align-items: center;
background-color: ${theme.components.grey};
padding: 1rem 2rem;
margin-right: 2rem;
border-radius: 0.4rem;
}
.ingredient-name {
display: flex;
}
input {
padding-bottom: 1rem;
border: none;
border-bottom: 1px solid ${theme.colors.lightGrey};
font-family: 'Source Sans Pro', sans-serif;
font-weight: 300;
}
`
I tried to take screenshots of the behaviour that I currently have. If I try to drag the 'bonjour' to the first position, the 1st item 'hello' does not move downwards. Instead what happens onReorder, what you see in the second picture, the bonjour and hello abruptly switch and it looks as though I am dragging the 'hello' item

MUI v5 migration - replacing withStyles and createStyles with styled utility

I am trying to migrate my MUI v4 to v5
Trying to replace all those utilities e.g. withStyles, createStyles and makeStyles
my existing code is as below:
export const DrawerThumbnail = withStyles(() =>
createStyles({
drawerPaper: {
width: '200px',
top: 112,
backgroundColor: Color.White,
border: 'none',
marginTop: '2px',
padding: '0px 5px 0px 5px',
},
})
)(({ classes, ...props }: any) => {
return (
<Drawer
variant="permanent"
classes={{
paper: classes.drawerPaper,
}}
anchor="left"
{...props}
/>
);
});
Trying to use styled utility from #mui/system
The new code looks like this but obviously it doesn't work as I don't know how to transform the above using styled utility.
export const DrawerThumbnail2 = styled((props: any) =>
<Drawer
variant="permanent"
anchor="left"
{...props}
/>
)`
width: '200px';
top: 112;
background-color: ${Color.White};
border: 'none';
margin-top: '2px';
padding: 0px 5px 0px 5px;
`;
Please help

transition in svelte is working only in the first time

i'm doing the Free Code Camp "Random Quote Machine" project in svelte
here :
https://learn.freecodecamp.org/front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine
I try to do a "scale" transition to the quote component. the transition is working only on the first time. I understand that I need to create and destroy the DOM element every time , like it is in the documentation :
"A transition is triggered by an element entering or leaving the DOM as a result of a state change".
how to do it correct ?
my App component :
<script>
import {onMount} from 'svelte'
import Quote from './Quote.svelte'
import Button from './Button.svelte'
let quotes=""
let quote=""
onMount(async ()=> {
const res=await fetch('https://gist.githubusercontent.com/natebass/b0a548425a73bdf8ea5c618149fe1fce/raw/f4231cd5961f026264bb6bb3a6c41671b044f1f4/quotes.json')
quotes=await res.json()
let r=Math.ceil(Math.random()*quotes.length)
quote= quotes[r]
})
const handleClick=()=>{
quote=quotes[Math.ceil(Math.random()*quotes.length)]
}
</script>
<style>
#quote-box {
margin: 50px auto;
width: 50%;
border: 3px solid green;
padding: 10px;
text-align: center;
background: whitesmoke;
}
</style>
<div id="quote-box">
<Quote {quote} />
<Button on:newQ={handleClick}
id="new-quote">New Quote</Button>
<Button
href="{`https://twitter.com/intent/tweet?text="${quote.quote}"-${quote.author}`}"
{quote} id="tweet-quote">
Twit</Button>
</div>
my Button component (it's the same component to the "twit" button with "a" tag, and to the newQuote button):
<script>
import { createEventDispatcher } from 'svelte';
export let href
export let quote
export let id
export let color
const dispatch=createEventDispatcher()
function twit() {
dispatch('twit',"");
}
function newQuote() {
dispatch('newQ',"");
}
</script>
<style>
button, a {
/* background-color:#008CBA; */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border-radius: 10px;
}
#tweet-quote{
background-color:#008CBA;
}
#new-quote {
background-color: #f44336;
}
</style>
{#if href}
<a {id} target="_blank" {href} ><slot/></a>
{:else }
<button {id} on:click={newQuote}><slot/></button>
{/if}
my Quote component :
<script>
import { scale } from 'svelte/transition';
export let quote
</script>
{#if quote}
<div class="container" transition:scale>
<p id="text">{quote.quote}</p>
<p id="author">{quote.author}</p>
</div >
{:else}
<p>loading</p>
{/if}
One quite simple way to do this is to set the quote to null, hiding the element, and then wait for a timeout before updating the quote, resulting in the div hiding and re-appearing REPL example

How to remove focused highlight in React material-ui Tab Component?

I am using a Tab component from the react Material-ui library. The tab appears with this weird outline on the left and right borders when the Tab element is in focus.
Is there any way to remove this active / focus outline?
Below is an image of the weird focus styling in question
My code is below:
import { Fragment } from 'react';
import styled from 'styled-components'
import Card from 'components/Elements/Card';
import CardItem from 'components/Elements/CardItem';
import CreateAccountForm from 'components/Forms/CreateAccount/container';
import { withTheme } from 'styled-components';
import { Container, Row, Col } from 'styled-bootstrap-grid';
import { pure } from 'recompact';
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import { withStyles } from '#material-ui/core/styles';
import AppBar from '#material-ui/core/AppBar';
import OpenModalButton from 'components/Modal/OpenModalButton/container';
const styles = theme => ({
indicator: {
backgroundColor: "red",
border: '5px solid blue !important',
'&:active': {
outline: 'none',
},
'&:focus': {
outline: 'none',
}
},
selected: {
backgroundColor: 'blue',
},
wrapper: {
border: '5px solid blue',
}
});
import { LogoElement } from 'components/Elements/Icons';
const StyledCard = styled(withTheme(Card))`
border: 15px solid ${ props => props.theme.colors.blue[3]};
text-align: left;
border-radius: 3px;
padding-top: ${ props => props.theme.spacer[2]};
padding-bottom: ${ props => props.theme.spacer[2]};
position: relative;
width: 98%;
max-width: 1250px;
min-height: 600px;
display: flex;
align-items: flex-start;
h5 {
color: ${ ({ theme }) => theme.colors.orange[3]};
}
`;
const CloseButton = styled.a`
transform: rotate(45deg);
font-size: 50px !important;
border: none !important;
position: absolute;
top: -20px;
right: 5px;
color: ${ props => props.theme.colors.blue[3]} !important;
font-weight: 200 !important;
&:hover{
text-decoration: none;
}
`;
const LogoContainer = styled.div`
position: absolute;
top: 10px;
left: 15px;
width: 45px;
height: 100%;
svg, path, g, polygon, rect {
fill: ${ props => props.theme.colors.orange[1]} !important;
}
`;
const Renderer = ({ handleClose, className, classes, handleTabChangeClick }) => {
return (
<StyledCard>
<CloseButton href="#" onClick={handleClose}>+</CloseButton>
<CardItem>
<Container>
<Row>
<Col>
<Tabs
variant="fullWidth"
onChange={handleTabChangeClick}
>
<Tab label="Profile" />
<Tab label="Activity" />
<Tab label="Score" />
<Tab label="Edit" />
</Tabs>
</Col>
</Row>
</Container>
</CardItem>
</StyledCard>
);
};
export default withStyles(styles)(Renderer);
I had the same problem. Try changing:
'&:active': {
outline: 'none',
},
To:
'&:hover': {
outline: 'none',
},
I use styled-components to override material-ui styling, so my setup is a little different, but the solution should be the same.
You have to override Mui-selected class.
'&.Mui-selected': {
outline: 'none',
}
See https://material-ui.com/api/tab/#css for classes defined for tab.
This solved my issue.
<Tabs value={value} onChange={handleChange} aria-label="basic tabs example">
<Tab sx={{
'&.Mui-selected': {
outline: 'none',
}
}}
label="Item One" />
<Tab sx={{
'&.Mui-selected': {
outline: 'none',
}
}} label="Item Two" />
<Tab sx={{
'&.Mui-selected': {
outline: 'none',
}
}}
label="Item Three" />
</Tabs>
If you are facing the issue in a textarea in MUI, add the following to the inline style:
--Textarea-focusedHighlight":"none"
For instance,
<Textarea maxRows={10} style={{"--Textarea-focusedHighlight":"none"}} placeholder="Write your answers here" />

How to change the width or other css styles of a div in angular 5 by clicking a button?

I am trying to load a full width navigation bar by clicking a menu icon. And i am using angular 5. I have tried googling about DOM manipulation in angular 5+ versions but its really confusing and complicated.
My question is about how can i change or manipulate these html elements using angular(typescript) like we used to do with plain javascript and JQuery.
My question is all about changing the width of a div but i want to know how can i work with other css styles and DOM manipulation techniques.
Here is my code
home.component.html
<section id="top">
<div id="menu">
<a id="toggle" (click)="openMenu()" >
<i class="fa fa-bars menu-bar" aria-hidden="true"></i>
</a>
</div>
<div id="sidenav" class="overlay" ref="#sidenav">
×
<div class="overlay-content">
About
Services
Clients
Contact
</div>
</div>
<div id="heading">
<div id="logo">Koa</div>
<div id="tagline">next generation web framework for node.js</div>
</div>
</section>
home.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
styles.scss
/* You can add global styles to this file, and also import other style files */
#import "~bootswatch/dist/lux/_variables.scss";
#import "~bootstrap/scss/bootstrap.scss";
#import "~bootswatch/dist/lux/_bootswatch.scss";
body {
background-color: #F5F5F5;
}
//navbar
#menu {
position: fixed;
top: 35px;
right: 42px;
z-index: 50;
}
#menu a#toggle {
position: absolute;
top: 0;
right: 0;
padding: 15px;
background:transparent;
border-radius: 2px;
border: 1px solid transparent;
z-index: 5;
font-size: 1.3rem;
color: black;
}
//sidenav
.overlay {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0, 0.9);
overflow-x: hidden;
transition: 0.5s;
}
.overlay-content {
position: relative;
top: 25%;
width: 100%;
text-align: center;
margin-top: 30px;
}
.overlay a {
padding: 8px;
text-decoration: none;
font-size: 36px;
color: #818181;
display: block;
transition: 0.3s;
}
.overlay a:hover, .overlay a:focus {
color: #f1f1f1;
}
.overlay .closebtn {
position: absolute;
top: 20px;
right: 45px;
font-size: 60px;
}
#media screen and (max-height: 450px) {
.overlay a {font-size: 20px}
.overlay .closebtn {
font-size: 40px;
top: 15px;
right: 35px;
}
}
//heading or showcase
#heading {
position: absolute;
top: 50%;
margin-top: -150px;
text-align: center;
width: 100%;
}
#logo {
font: 150px 'Italiana', sans-serif;
text-transform: lowercase;
}
#tagline {
font-size: 16px;
}
You can use [ngClass]="{'scssClassName': condition}" for conditioning class appendance on div like this:
<div class="existingClassWithNormalWidth" [ngClass]="{'scssClassNameWithFullWidth': condition}">{{childTags}}</div>.
You can also give different classes for different conditions on same tags like this: [ngClass]="{'scssClassName': condition, 'scssClassName2': condition2, 'scssClassName3': anyBooleanVariable,}"
You can set condition(or boolean) to be true by clicking button. Angular will automatically append the class to div itself.
You can also use [ngStyle] for only full width, but if you want to give extra style, you better make a class to SCSS and use [ngClass].
Find official doc for class https://angular.io/api/common/NgClass
(If you want to append class)
Find official doc for style only https://angular.io/api/common/NgStyle
(If only you want to make full width with ngStyle)