New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

dom-testing-library

Package Overview
Dependencies
Maintainers
1
Versions
93
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

dom-testing-library - npm Package Compare versions

Comparing version 3.18.2 to 3.19.0

80

dist/__tests__/config.js

@@ -1,57 +0,55 @@

"use strict";
import {configure, getConfig} from '../config'
var _config = require("../config");
describe('configuration API', () => {
let originalConfig;
let originalConfig
beforeEach(() => {
// Grab the existing configuration so we can restore
// it at the end of the test
(0, _config.configure)(existingConfig => {
originalConfig = existingConfig; // Don't change the existing config
configure(existingConfig => {
originalConfig = existingConfig
// Don't change the existing config
return {}
})
})
afterEach(() => {
configure(originalConfig)
})
return {};
});
});
afterEach(() => {
(0, _config.configure)(originalConfig);
});
beforeEach(() => {
(0, _config.configure)({
other: 123
});
});
configure({other: 123})
})
describe('getConfig', () => {
test('returns existing configuration', () => {
const conf = (0, _config.getConfig)();
expect(conf.testIdAttribute).toEqual('data-testid');
});
});
const conf = getConfig()
expect(conf.testIdAttribute).toEqual('data-testid')
})
})
describe('configure', () => {
test('merges a delta rather than replacing the whole config', () => {
const conf = (0, _config.getConfig)();
expect(conf).toMatchObject({
testIdAttribute: 'data-testid'
});
});
const conf = getConfig()
expect(conf).toMatchObject({testIdAttribute: 'data-testid'})
})
test('overrides existing values', () => {
(0, _config.configure)({
testIdAttribute: 'new-id'
});
const conf = (0, _config.getConfig)();
expect(conf.testIdAttribute).toEqual('new-id');
});
configure({testIdAttribute: 'new-id'})
const conf = getConfig()
expect(conf.testIdAttribute).toEqual('new-id')
})
test('passes existing config out to config function', () => {
// Create a new config key based on the value of an existing one
(0, _config.configure)(existingConfig => ({
testIdAttribute: `${existingConfig.testIdAttribute}-derived`
}));
const conf = (0, _config.getConfig)(); // The new value should be there, and existing values should be
configure(existingConfig => ({
testIdAttribute: `${existingConfig.testIdAttribute}-derived`,
}))
const conf = getConfig()
// The new value should be there, and existing values should be
// untouched
expect(conf).toMatchObject({
testIdAttribute: 'data-testid-derived'
});
});
});
});
testIdAttribute: 'data-testid-derived',
})
})
})
})

@@ -1,10 +0,8 @@

"use strict";
import {configure} from '../config'
import {render, renderIntoDocument} from './helpers/test-utils'
var _config = require("../config");
beforeEach(() => {
document.defaultView.Cypress = null
})
var _testUtils = require("./helpers/test-utils");
beforeEach(() => {
document.defaultView.Cypress = null;
});
test('query can return null', () => {

@@ -17,11 +15,12 @@ const {

queryByTestId,
queryByAltText
} = (0, _testUtils.render)('<div />');
expect(queryByTestId('LucyRicardo')).toBeNull();
expect(queryByLabelText('LucyRicardo')).toBeNull();
expect(queryBySelectText('LucyRicardo')).toBeNull();
expect(queryByPlaceholderText('LucyRicardo')).toBeNull();
expect(queryByText('LucyRicardo')).toBeNull();
expect(queryByAltText('LucyRicardo')).toBeNull();
});
queryByAltText,
} = render('<div />')
expect(queryByTestId('LucyRicardo')).toBeNull()
expect(queryByLabelText('LucyRicardo')).toBeNull()
expect(queryBySelectText('LucyRicardo')).toBeNull()
expect(queryByPlaceholderText('LucyRicardo')).toBeNull()
expect(queryByText('LucyRicardo')).toBeNull()
expect(queryByAltText('LucyRicardo')).toBeNull()
})
test('get throws a useful error message', () => {

@@ -37,5 +36,6 @@ const {

getByValue,
getByRole
} = (0, _testUtils.render)('<div />');
expect(() => getByLabelText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`
getByRole,
} = render('<div />')
expect(() => getByLabelText('LucyRicardo'))
.toThrowErrorMatchingInlineSnapshot(`
"Unable to find a label with the text of: LucyRicardo

@@ -46,4 +46,5 @@

</div>"
`);
expect(() => getBySelectText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`
`)
expect(() => getBySelectText('LucyRicardo'))
.toThrowErrorMatchingInlineSnapshot(`
"Unable to find a <select> element with the selected option's text: LucyRicardo

@@ -54,4 +55,5 @@

</div>"
`);
expect(() => getByPlaceholderText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`
`)
expect(() => getByPlaceholderText('LucyRicardo'))
.toThrowErrorMatchingInlineSnapshot(`
"Unable to find an element with the placeholder text of: LucyRicardo

@@ -62,3 +64,3 @@

</div>"
`);
`)
expect(() => getByText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`

@@ -70,3 +72,3 @@ "Unable to find an element with the text: LucyRicardo. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

</div>"
`);
`)
expect(() => getByTestId('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`

@@ -78,3 +80,3 @@ "Unable to find an element by: [data-testid=\\"LucyRicardo\\"]

</div>"
`);
`)
expect(() => getByAltText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`

@@ -86,3 +88,3 @@ "Unable to find an element with the alt text: LucyRicardo

</div>"
`);
`)
expect(() => getByTitle('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`

@@ -94,3 +96,3 @@ "Unable to find an element with the title: LucyRicardo.

</div>"
`);
`)
expect(() => getByValue('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`

@@ -102,3 +104,3 @@ "Unable to find an element with the value: LucyRicardo.

</div>"
`);
`)
expect(() => getByRole('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`

@@ -110,8 +112,7 @@ "Unable to find an element by role=LucyRicardo

</div>"
`);
});
`)
})
test('can get elements by matching their text content', () => {
const {
queryByText
} = (0, _testUtils.render)(`
const {queryByText} = render(`
<div>

@@ -125,20 +126,21 @@ <span>Currently showing</span>

</div>
`);
expect(queryByText('Currently showing')).toBeTruthy();
expect(queryByText('Step 1 of 4')).toBeTruthy();
});
`)
expect(queryByText('Currently showing')).toBeTruthy()
expect(queryByText('Step 1 of 4')).toBeTruthy()
})
test('can get elements by matching their text across adjacent text nodes', () => {
const textDiv = document.createElement('div');
['£', '24', '.', '99'].map(text => document.createTextNode(text)).forEach(textNode => textDiv.appendChild(textNode));
const {
container,
queryByText
} = (0, _testUtils.render)('<div />');
container.appendChild(textDiv);
expect(queryByText('£24.99')).toBeTruthy();
});
const textDiv = document.createElement('div')
const textNodeContent = ['£', '24', '.', '99']
textNodeContent
.map(text => document.createTextNode(text))
.forEach(textNode => textDiv.appendChild(textNode))
const {container, queryByText} = render('<div />')
container.appendChild(textDiv)
expect(queryByText('£24.99')).toBeTruthy()
})
test('can get input elements with type submit or button', () => {
const {
queryByText
} = (0, _testUtils.render)(`
const {queryByText} = render(`
<div>

@@ -149,20 +151,18 @@ <input type="submit" value="Send data"/>

</div>
`);
expect(queryByText('Send data')).toBeTruthy();
expect(queryByText('Push me!')).toBeTruthy();
expect(queryByText('user data')).toBeFalsy();
});
`)
expect(queryByText('Send data')).toBeTruthy()
expect(queryByText('Push me!')).toBeTruthy()
expect(queryByText('user data')).toBeFalsy()
})
test('matches case with RegExp matcher', () => {
const {
queryByText
} = (0, _testUtils.render)(`
const {queryByText} = render(`
<span>STEP 1 of 4</span>
`);
expect(queryByText(/STEP 1 of 4/)).toBeTruthy();
expect(queryByText(/Step 1 of 4/)).not.toBeTruthy();
});
`)
expect(queryByText(/STEP 1 of 4/)).toBeTruthy()
expect(queryByText(/Step 1 of 4/)).not.toBeTruthy()
})
test('can get form controls by label text', () => {
const {
getByLabelText
} = (0, _testUtils.render)(`
const {getByLabelText} = render(`
<div>

@@ -191,15 +191,13 @@ <label>

</div>
`);
expect(getByLabelText('1st').id).toBe('first-id');
expect(getByLabelText('2nd').id).toBe('second-id');
expect(getByLabelText('3rd').id).toBe('third-id');
expect(getByLabelText('4th').id).toBe('fourth.id');
expect(getByLabelText('5th one').id).toBe('fifth-id');
expect(getByLabelText('5th two').id).toBe('fifth-id');
});
`)
expect(getByLabelText('1st').id).toBe('first-id')
expect(getByLabelText('2nd').id).toBe('second-id')
expect(getByLabelText('3rd').id).toBe('third-id')
expect(getByLabelText('4th').id).toBe('fourth.id')
expect(getByLabelText('5th one').id).toBe('fifth-id')
expect(getByLabelText('5th two').id).toBe('fifth-id')
})
test('can get elements labelled with aria-labelledby attribute', () => {
const {
getByLabelText,
getAllByLabelText
} = (0, _testUtils.render)(`
const {getByLabelText, getAllByLabelText} = render(`
<div>

@@ -215,22 +213,21 @@ <h1 id="content-header">The Gettysburg Address</h1>

</div>
`);
const result = getAllByLabelText('The Gettysburg Address').map(el => el.id);
expect(result).toHaveLength(2);
expect(result).toEqual(expect.arrayContaining(['sibling-of-content-header', 'section-one']));
expect(getByLabelText('Section One').id).toBe('section-one');
});
`)
const result = getAllByLabelText('The Gettysburg Address').map(el => el.id)
expect(result).toHaveLength(2)
expect(result).toEqual(
expect.arrayContaining(['sibling-of-content-header', 'section-one']),
)
expect(getByLabelText('Section One').id).toBe('section-one')
})
test('get can get form controls by placeholder', () => {
const {
getByPlaceholderText
} = (0, _testUtils.render)(`
const {getByPlaceholderText} = render(`
<input id="username-id" placeholder="username" />,
`);
expect(getByPlaceholderText('username').id).toBe('username-id');
});
`)
expect(getByPlaceholderText('username').id).toBe('username-id')
})
test('label with no form control', () => {
const {
getByLabelText,
queryByLabelText
} = (0, _testUtils.render)(`<label>All alone</label>`);
expect(queryByLabelText(/alone/)).toBeNull();
const {getByLabelText, queryByLabelText} = render(`<label>All alone</label>`)
expect(queryByLabelText(/alone/)).toBeNull()
expect(() => getByLabelText(/alone/)).toThrowErrorMatchingInlineSnapshot(`

@@ -244,10 +241,8 @@ "Found a label with the text of: /alone/, however no form control was found associated to that label. Make sure you're using the \\"for\\" attribute or \\"aria-labelledby\\" attribute correctly.

</div>"
`);
});
`)
})
test('totally empty label', () => {
const {
getByLabelText,
queryByLabelText
} = (0, _testUtils.render)(`<label />`);
expect(queryByLabelText('')).toBeNull();
const {getByLabelText, queryByLabelText} = render(`<label />`)
expect(queryByLabelText('')).toBeNull()
expect(() => getByLabelText('')).toThrowErrorMatchingInlineSnapshot(`

@@ -259,15 +254,13 @@ "Found a label with the text of: , however no form control was found associated to that label. Make sure you're using the \\"for\\" attribute or \\"aria-labelledby\\" attribute correctly.

</div>"
`);
});
`)
})
test('getByLabelText with aria-label', () => {
// not recommended normally, but supported for completeness
const {
queryByLabelText
} = (0, _testUtils.render)(`<input aria-label="batman" />`);
expect(queryByLabelText(/bat/)).toBeTruthy();
});
const {queryByLabelText} = render(`<input aria-label="batman" />`)
expect(queryByLabelText(/bat/)).toBeTruthy()
})
test('get element by its alt text', () => {
const {
getByAltText
} = (0, _testUtils.render)(`
const {getByAltText} = render(`
<div>

@@ -277,10 +270,8 @@ <input data-info="no alt here" />

</div>,
`);
expect(getByAltText(/fin.*nem.*poster$/i).src).toContain('/finding-nemo.png');
});
`)
expect(getByAltText(/fin.*nem.*poster$/i).src).toContain('/finding-nemo.png')
})
test('query/get element by its title', () => {
const {
getByTitle,
queryByTitle
} = (0, _testUtils.render)(`
const {getByTitle, queryByTitle} = render(`
<div>

@@ -291,14 +282,11 @@ <span title="Ignore this" id="1"/>

</div>
`);
expect(getByTitle('Delete').id).toEqual('2');
expect(queryByTitle('Delete').id).toEqual('2');
expect(queryByTitle('Del', {
exact: false
}).id).toEqual('2');
});
`)
expect(getByTitle('Delete').id).toEqual('2')
expect(queryByTitle('Delete').id).toEqual('2')
expect(queryByTitle('Del', {exact: false}).id).toEqual('2')
})
test('query/get title element of SVG', () => {
const {
getByTitle,
queryByTitle
} = (0, _testUtils.render)(`
const {getByTitle, queryByTitle} = render(`
<div>

@@ -312,11 +300,10 @@ <svg>

</div>
`);
expect(getByTitle('Close').id).toEqual('svg-title');
expect(queryByTitle('Close').id).toEqual('svg-title');
});
`)
expect(getByTitle('Close').id).toEqual('svg-title')
expect(queryByTitle('Close').id).toEqual('svg-title')
})
test('query/get element by its value', () => {
const {
getByValue,
queryByValue
} = (0, _testUtils.render)(`
const {getByValue, queryByValue} = render(`
<div>

@@ -327,11 +314,10 @@ <input placeholder="name" type="text"/>

</div>
`);
expect(getByValue('Norris').placeholder).toEqual('lastname');
expect(queryByValue('Norris').placeholder).toEqual('lastname');
});
`)
expect(getByValue('Norris').placeholder).toEqual('lastname')
expect(queryByValue('Norris').placeholder).toEqual('lastname')
})
test('query/get select by text with the default option selected', () => {
const {
getBySelectText,
queryBySelectText
} = (0, _testUtils.render)(`
const {getBySelectText, queryBySelectText} = render(`
<select id="state-select">

@@ -343,11 +329,10 @@ <option value="">State</option>

</select>
`);
expect(getBySelectText('State').id).toEqual('state-select');
expect(queryBySelectText('State').id).toEqual('state-select');
});
`)
expect(getBySelectText('State').id).toEqual('state-select')
expect(queryBySelectText('State').id).toEqual('state-select')
})
test('query/get select by text with one option selected', () => {
const {
getBySelectText,
queryBySelectText
} = (0, _testUtils.render)(`
const {getBySelectText, queryBySelectText} = render(`
<select id="state-select">

@@ -359,11 +344,10 @@ <option value="">State</option>

</select>
`);
expect(getBySelectText('Alaska').id).toEqual('state-select');
expect(queryBySelectText('Alaska').id).toEqual('state-select');
});
`)
expect(getBySelectText('Alaska').id).toEqual('state-select')
expect(queryBySelectText('Alaska').id).toEqual('state-select')
})
test('query/get select by text with multiple options selected', () => {
const {
getBySelectText,
queryBySelectText
} = (0, _testUtils.render)(`
const {getBySelectText, queryBySelectText} = render(`
<select multiple id="state-select">

@@ -375,41 +359,38 @@ <option value="">State</option>

</select>
`);
expect(getBySelectText('Alabama').id).toEqual('state-select');
expect(queryBySelectText('Alaska').id).toEqual('state-select');
});
`)
expect(getBySelectText('Alabama').id).toEqual('state-select')
expect(queryBySelectText('Alaska').id).toEqual('state-select')
})
describe('query by test id', () => {
test('can get elements by test id', () => {
const {
queryByTestId
} = (0, _testUtils.render)(`<div data-testid="firstName"></div>`);
expect(queryByTestId('firstName')).toBeTruthy();
expect(queryByTestId(/first/)).toBeTruthy();
expect(queryByTestId(testid => testid === 'firstName')).toBeTruthy(); // match should be exact, case-sensitive
const {queryByTestId} = render(`<div data-testid="firstName"></div>`)
expect(queryByTestId('firstName')).toBeTruthy()
expect(queryByTestId(/first/)).toBeTruthy()
expect(queryByTestId(testid => testid === 'firstName')).toBeTruthy()
// match should be exact, case-sensitive
expect(queryByTestId('firstname')).not.toBeTruthy()
expect(queryByTestId('first')).not.toBeTruthy()
expect(queryByTestId('firstNamePlusMore')).not.toBeTruthy()
expect(queryByTestId('first-name')).not.toBeTruthy()
})
expect(queryByTestId('firstname')).not.toBeTruthy();
expect(queryByTestId('first')).not.toBeTruthy();
expect(queryByTestId('firstNamePlusMore')).not.toBeTruthy();
expect(queryByTestId('first-name')).not.toBeTruthy();
});
test('can override test id attribute', () => {
const {
queryByTestId
} = (0, _testUtils.render)(`<div data-my-test-id="theTestId"></div>`);
(0, _config.configure)({
testIdAttribute: 'data-my-test-id'
});
expect(queryByTestId('theTestId')).toBeTruthy();
(0, _config.configure)({
testIdAttribute: 'something-else'
});
expect(queryByTestId('theTestId')).toBeFalsy();
});
const {queryByTestId} = render(`<div data-my-test-id="theTestId"></div>`)
configure({testIdAttribute: 'data-my-test-id'})
expect(queryByTestId('theTestId')).toBeTruthy()
configure({testIdAttribute: 'something-else'})
expect(queryByTestId('theTestId')).toBeFalsy()
})
afterEach(() => {
// Restore the default test id attribute
// even if these tests failed
(0, _config.configure)({
testIdAttribute: 'data-testid'
});
});
});
configure({testIdAttribute: 'data-testid'})
})
})
test('getAll* matchers return an array', () => {

@@ -423,4 +404,4 @@ const {

getAllByText,
getAllByRole
} = (0, _testUtils.render)(`
getAllByRole,
} = render(`
<div role="container">

@@ -453,13 +434,14 @@ <img

</div>,
`);
expect(getAllByAltText(/finding.*poster$/i)).toHaveLength(2);
expect(getAllByAltText(/jumanji/)).toHaveLength(1);
expect(getAllByTestId('poster')).toHaveLength(3);
expect(getAllByPlaceholderText(/The Rock/)).toHaveLength(1);
expect(getAllByLabelText('User Name')).toHaveLength(1);
expect(getAllBySelectText('Japanese cars')).toHaveLength(1);
expect(getAllBySelectText(/cars$/)).toHaveLength(2);
expect(getAllByText(/^where/i)).toHaveLength(1);
expect(getAllByRole(/container/i)).toHaveLength(1);
});
`)
expect(getAllByAltText(/finding.*poster$/i)).toHaveLength(2)
expect(getAllByAltText(/jumanji/)).toHaveLength(1)
expect(getAllByTestId('poster')).toHaveLength(3)
expect(getAllByPlaceholderText(/The Rock/)).toHaveLength(1)
expect(getAllByLabelText('User Name')).toHaveLength(1)
expect(getAllBySelectText('Japanese cars')).toHaveLength(1)
expect(getAllBySelectText(/cars$/)).toHaveLength(2)
expect(getAllByText(/^where/i)).toHaveLength(1)
expect(getAllByRole(/container/i)).toHaveLength(1)
})
test('getAll* matchers throw for 0 matches', () => {

@@ -474,19 +456,20 @@ const {

getAllByRole,
getAllByDisplayValue
} = (0, _testUtils.render)(`
getAllByDisplayValue,
} = render(`
<div role="container">
<label>No Matches Please</label>
</div>,
`);
expect(() => getAllByTestId('nope')).toThrow();
expect(() => getAllByTestId('abc')).toThrow();
expect(() => getAllByAltText('nope')).toThrow();
expect(() => getAllByLabelText('nope')).toThrow();
expect(() => getAllByLabelText('no matches please')).toThrow();
expect(() => getAllBySelectText('nope')).toThrow();
expect(() => getAllByPlaceholderText('nope')).toThrow();
expect(() => getAllByText('nope')).toThrow();
expect(() => getAllByRole('nope')).toThrow();
expect(() => getAllByDisplayValue('nope')).toThrow();
});
`)
expect(() => getAllByTestId('nope')).toThrow()
expect(() => getAllByTestId('abc')).toThrow()
expect(() => getAllByAltText('nope')).toThrow()
expect(() => getAllByLabelText('nope')).toThrow()
expect(() => getAllByLabelText('no matches please')).toThrow()
expect(() => getAllBySelectText('nope')).toThrow()
expect(() => getAllByPlaceholderText('nope')).toThrow()
expect(() => getAllByText('nope')).toThrow()
expect(() => getAllByRole('nope')).toThrow()
expect(() => getAllByDisplayValue('nope')).toThrow()
})
test('queryAll* matchers return an array for 0 matches', () => {

@@ -500,76 +483,91 @@ const {

queryAllByText,
queryAllByRole
} = (0, _testUtils.render)(`
queryAllByRole,
} = render(`
<div>
</div>,
`);
expect(queryAllByTestId('nope')).toHaveLength(0);
expect(queryAllByAltText('nope')).toHaveLength(0);
expect(queryAllByLabelText('nope')).toHaveLength(0);
expect(queryAllBySelectText('nope')).toHaveLength(0);
expect(queryAllByPlaceholderText('nope')).toHaveLength(0);
expect(queryAllByText('nope')).toHaveLength(0);
expect(queryAllByRole('nope')).toHaveLength(0);
});
`)
expect(queryAllByTestId('nope')).toHaveLength(0)
expect(queryAllByAltText('nope')).toHaveLength(0)
expect(queryAllByLabelText('nope')).toHaveLength(0)
expect(queryAllBySelectText('nope')).toHaveLength(0)
expect(queryAllByPlaceholderText('nope')).toHaveLength(0)
expect(queryAllByText('nope')).toHaveLength(0)
expect(queryAllByRole('nope')).toHaveLength(0)
})
test('queryAllByText can query dom nodes', () => {
const {
queryAllByText
} = (0, _testUtils.render)('hi');
expect(queryAllByText('hi')).toHaveLength(1);
expect(queryAllByText('not here')).toHaveLength(0);
expect(queryAllByText('hi', {
selector: 'span'
})).toHaveLength(0);
});
const {queryAllByText} = render('hi')
expect(queryAllByText('hi')).toHaveLength(1)
expect(queryAllByText('not here')).toHaveLength(0)
expect(queryAllByText('hi', {selector: 'span'})).toHaveLength(0)
})
test('queryAllByText works with document container', () => {
// This is required for Cypress as it uses `document`
// as the container for all methods
const {
queryAllByText
} = (0, _testUtils.renderIntoDocument)('<p>hello</p>');
expect(queryAllByText('hello')).toHaveLength(1);
expect(queryAllByText('not here')).toHaveLength(0);
expect(queryAllByText('hello', {
selector: 'span'
})).toHaveLength(0);
});
const {queryAllByText} = renderIntoDocument('<p>hello</p>')
expect(queryAllByText('hello')).toHaveLength(1)
expect(queryAllByText('not here')).toHaveLength(0)
expect(queryAllByText('hello', {selector: 'span'})).toHaveLength(0)
})
test('using jest helpers to assert element states', () => {
const {
queryByTestId
} = (0, _testUtils.render)(`<span data-testid="count-value">2</span>`); // other ways to assert your test cases, but you don't need all of them.
const {queryByTestId} = render(`<span data-testid="count-value">2</span>`)
expect(queryByTestId('count-value')).toBeTruthy();
expect(queryByTestId('count-value1')).not.toBeTruthy();
expect(queryByTestId('count-value')).toHaveTextContent('2');
expect(queryByTestId('count-value')).not.toHaveTextContent('21');
expect(() => expect(queryByTestId('count-value2')).toHaveTextContent('2')).toThrowError(); // negative test cases wrapped in throwError assertions for coverage.
// other ways to assert your test cases, but you don't need all of them.
expect(queryByTestId('count-value')).toBeTruthy()
expect(queryByTestId('count-value1')).not.toBeTruthy()
expect(queryByTestId('count-value')).toHaveTextContent('2')
expect(queryByTestId('count-value')).not.toHaveTextContent('21')
expect(() =>
expect(queryByTestId('count-value2')).toHaveTextContent('2'),
).toThrowError()
expect(() => expect(queryByTestId('count-value')).not.toBeTruthy()).toThrowError();
expect(() => expect(queryByTestId('count-value1')).toBeTruthy()).toThrowError();
expect(() => expect(queryByTestId('count-value')).toHaveTextContent('3')).toThrowError();
expect(() => expect(queryByTestId('count-value')).not.toHaveTextContent('2')).toThrowError();
});
// negative test cases wrapped in throwError assertions for coverage.
expect(() =>
expect(queryByTestId('count-value')).not.toBeTruthy(),
).toThrowError()
expect(() =>
expect(queryByTestId('count-value1')).toBeTruthy(),
).toThrowError()
expect(() =>
expect(queryByTestId('count-value')).toHaveTextContent('3'),
).toThrowError()
expect(() =>
expect(queryByTestId('count-value')).not.toHaveTextContent('2'),
).toThrowError()
})
test('using jest helpers to check element attributes', () => {
const {
getByTestId
} = (0, _testUtils.render)(`
const {getByTestId} = render(`
<button data-testid="ok-button" type="submit" disabled>
OK
</button>
`);
expect(getByTestId('ok-button')).toHaveAttribute('disabled');
expect(getByTestId('ok-button')).toHaveAttribute('type');
expect(getByTestId('ok-button')).not.toHaveAttribute('class');
expect(getByTestId('ok-button')).toHaveAttribute('type', 'submit');
expect(getByTestId('ok-button')).not.toHaveAttribute('type', 'button');
expect(() => expect(getByTestId('ok-button')).not.toHaveAttribute('disabled')).toThrowError();
expect(() => expect(getByTestId('ok-button')).not.toHaveAttribute('type')).toThrowError();
expect(() => expect(getByTestId('ok-button')).toHaveAttribute('class')).toThrowError();
expect(() => expect(getByTestId('ok-button')).not.toHaveAttribute('type', 'submit')).toThrowError();
expect(() => expect(getByTestId('ok-button')).toHaveAttribute('type', 'button')).toThrowError();
});
`)
expect(getByTestId('ok-button')).toHaveAttribute('disabled')
expect(getByTestId('ok-button')).toHaveAttribute('type')
expect(getByTestId('ok-button')).not.toHaveAttribute('class')
expect(getByTestId('ok-button')).toHaveAttribute('type', 'submit')
expect(getByTestId('ok-button')).not.toHaveAttribute('type', 'button')
expect(() =>
expect(getByTestId('ok-button')).not.toHaveAttribute('disabled'),
).toThrowError()
expect(() =>
expect(getByTestId('ok-button')).not.toHaveAttribute('type'),
).toThrowError()
expect(() =>
expect(getByTestId('ok-button')).toHaveAttribute('class'),
).toThrowError()
expect(() =>
expect(getByTestId('ok-button')).not.toHaveAttribute('type', 'submit'),
).toThrowError()
expect(() =>
expect(getByTestId('ok-button')).toHaveAttribute('type', 'button'),
).toThrowError()
})
test('using jest helpers to check element class names', () => {
const {
getByTestId
} = (0, _testUtils.render)(`
const {getByTestId} = render(`
<div>

@@ -583,64 +581,79 @@ <button data-testid="delete-button" class="btn extra btn-danger">

</div>
`);
expect(getByTestId('delete-button')).toHaveClass('btn');
expect(getByTestId('delete-button')).toHaveClass('btn-danger');
expect(getByTestId('delete-button')).toHaveClass('extra');
expect(getByTestId('delete-button')).not.toHaveClass('xtra');
expect(getByTestId('delete-button')).toHaveClass('btn btn-danger');
expect(getByTestId('delete-button')).not.toHaveClass('btn-link');
expect(getByTestId('cancel-button')).not.toHaveClass('btn-danger');
expect(() => expect(getByTestId('delete-button')).not.toHaveClass('btn')).toThrowError();
expect(() => expect(getByTestId('delete-button')).not.toHaveClass('btn-danger')).toThrowError();
expect(() => expect(getByTestId('delete-button')).not.toHaveClass('extra')).toThrowError();
expect(() => expect(getByTestId('delete-button')).toHaveClass('xtra')).toThrowError();
expect(() => expect(getByTestId('delete-button')).not.toHaveClass('btn btn-danger')).toThrowError();
expect(() => expect(getByTestId('delete-button')).toHaveClass('btn-link')).toThrowError();
expect(() => expect(getByTestId('cancel-button')).toHaveClass('btn-danger')).toThrowError();
});
`)
expect(getByTestId('delete-button')).toHaveClass('btn')
expect(getByTestId('delete-button')).toHaveClass('btn-danger')
expect(getByTestId('delete-button')).toHaveClass('extra')
expect(getByTestId('delete-button')).not.toHaveClass('xtra')
expect(getByTestId('delete-button')).toHaveClass('btn btn-danger')
expect(getByTestId('delete-button')).not.toHaveClass('btn-link')
expect(getByTestId('cancel-button')).not.toHaveClass('btn-danger')
expect(() =>
expect(getByTestId('delete-button')).not.toHaveClass('btn'),
).toThrowError()
expect(() =>
expect(getByTestId('delete-button')).not.toHaveClass('btn-danger'),
).toThrowError()
expect(() =>
expect(getByTestId('delete-button')).not.toHaveClass('extra'),
).toThrowError()
expect(() =>
expect(getByTestId('delete-button')).toHaveClass('xtra'),
).toThrowError()
expect(() =>
expect(getByTestId('delete-button')).not.toHaveClass('btn btn-danger'),
).toThrowError()
expect(() =>
expect(getByTestId('delete-button')).toHaveClass('btn-link'),
).toThrowError()
expect(() =>
expect(getByTestId('cancel-button')).toHaveClass('btn-danger'),
).toThrowError()
})
test('using jest helpers to check element role', () => {
const {
getByRole
} = (0, _testUtils.render)(`
const {getByRole} = render(`
<div role="dialog">
<span>Contents</span>
</div>
`);
expect(getByRole('dialog')).toHaveTextContent('Contents');
});
`)
expect(getByRole('dialog')).toHaveTextContent('Contents')
})
test('test the debug helper prints the dom state here', () => {
const originalDebugPrintLimit = process.env.DEBUG_PRINT_LIMIT;
const originalDebugPrintLimit = process.env.DEBUG_PRINT_LIMIT
const Large = `<div>
${Array.from({
length: 7000
}, (v, key) => key).map(() => {
return `<div data-testid="debugging" data-otherid="debugging">
${Array.from({length: 7000}, (v, key) => key).map(() => {
return `<div data-testid="debugging" data-otherid="debugging">
Hello World!
</div>`;
})}
</div>`;
const {
getByText
} = (0, _testUtils.renderIntoDocument)(Large); // render large DOM which exceeds 7000 limit
</div>`
})}
</div>`
expect(() => expect(getByText('not present')).toBeTruthy()).toThrowError();
const {getByText} = renderIntoDocument(Large) // render large DOM which exceeds 7000 limit
expect(() => expect(getByText('not present')).toBeTruthy()).toThrowError()
const Hello = `<div data-testid="debugging" data-otherid="debugging">
Hello World!
</div>`;
const {
getByTestId
} = (0, _testUtils.renderIntoDocument)(Hello);
process.env.DEBUG_PRINT_LIMIT = 5; // user should see `...`
</div>`
const {getByTestId} = renderIntoDocument(Hello)
process.env.DEBUG_PRINT_LIMIT = 5 // user should see `...`
expect(() => expect(getByTestId('not present')).toBeTruthy()).toThrowError(
/\.\.\.$/,
)
expect(() => expect(getByTestId('not present')).toBeTruthy()).toThrowError(/\.\.\.$/);
const {
getByLabelText
} = (0, _testUtils.renderIntoDocument)(Hello);
process.env.DEBUG_PRINT_LIMIT = 10000; // user shouldn't see `...`
const {getByLabelText} = renderIntoDocument(Hello)
process.env.DEBUG_PRINT_LIMIT = 10000 // user shouldn't see `...`
expect(() =>
expect(getByLabelText('not present')).toBeTruthy(/^((?!\.\.\.).)*$/),
).toThrowError()
expect(() => expect(getByLabelText('not present')).toBeTruthy(/^((?!\.\.\.).)*$/)).toThrowError(); //all good replacing it with old value
//all good replacing it with old value
process.env.DEBUG_PRINT_LIMIT = originalDebugPrintLimit
})
process.env.DEBUG_PRINT_LIMIT = originalDebugPrintLimit;
});
test('get throws a useful error message without DOM in Cypress', () => {
document.defaultView.Cypress = {};
document.defaultView.Cypress = {}
const {

@@ -654,30 +667,50 @@ getByLabelText,

getByTitle,
getByValue
} = (0, _testUtils.render)('<div />');
expect(() => getByLabelText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`"Unable to find a label with the text of: LucyRicardo"`);
expect(() => getBySelectText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`"Unable to find a <select> element with the selected option's text: LucyRicardo"`);
expect(() => getByPlaceholderText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`"Unable to find an element with the placeholder text of: LucyRicardo"`);
expect(() => getByText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`"Unable to find an element with the text: LucyRicardo. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible."`);
expect(() => getByTestId('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`"Unable to find an element by: [data-testid=\\"LucyRicardo\\"]"`);
expect(() => getByAltText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`"Unable to find an element with the alt text: LucyRicardo"`);
expect(() => getByTitle('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`"Unable to find an element with the title: LucyRicardo."`);
expect(() => getByValue('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`"Unable to find an element with the value: LucyRicardo."`);
});
getByValue,
} = render('<div />')
expect(() =>
getByLabelText('LucyRicardo'),
).toThrowErrorMatchingInlineSnapshot(
`"Unable to find a label with the text of: LucyRicardo"`,
)
expect(() =>
getBySelectText('LucyRicardo'),
).toThrowErrorMatchingInlineSnapshot(
`"Unable to find a <select> element with the selected option's text: LucyRicardo"`,
)
expect(() =>
getByPlaceholderText('LucyRicardo'),
).toThrowErrorMatchingInlineSnapshot(
`"Unable to find an element with the placeholder text of: LucyRicardo"`,
)
expect(() => getByText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(
`"Unable to find an element with the text: LucyRicardo. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible."`,
)
expect(() => getByTestId('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(
`"Unable to find an element by: [data-testid=\\"LucyRicardo\\"]"`,
)
expect(() => getByAltText('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(
`"Unable to find an element with the alt text: LucyRicardo"`,
)
expect(() => getByTitle('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(
`"Unable to find an element with the title: LucyRicardo."`,
)
expect(() => getByValue('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(
`"Unable to find an element with the value: LucyRicardo."`,
)
})
test('getByText ignores script tags by default', () => {
const {
getAllByText
} = (0, _testUtils.render)('<script>Hello</script><div>Hello</div><style>.Hello{}</style>');
const divOnly = getAllByText(/hello/i);
expect(divOnly).toHaveLength(1);
expect(divOnly[0].tagName).toBe('DIV');
const noScript = getAllByText(/hello/i, {
ignore: 'script'
});
expect(noScript[0].tagName).toBe('DIV');
expect(noScript[1].tagName).toBe('STYLE');
expect(noScript).toHaveLength(2);
expect(getAllByText(/hello/i, {
ignore: false
})).toHaveLength(3);
});
const {getAllByText} = render(
'<script>Hello</script><div>Hello</div><style>.Hello{}</style>',
)
const divOnly = getAllByText(/hello/i)
expect(divOnly).toHaveLength(1)
expect(divOnly[0].tagName).toBe('DIV')
const noScript = getAllByText(/hello/i, {ignore: 'script'})
expect(noScript[0].tagName).toBe('DIV')
expect(noScript[1].tagName).toBe('STYLE')
expect(noScript).toHaveLength(2)
expect(getAllByText(/hello/i, {ignore: false})).toHaveLength(3)
})
test('get/query input element by current value', () => {

@@ -687,17 +720,18 @@ const {

queryByDisplayValue,
getByTestId
} = (0, _testUtils.renderIntoDocument)(`
getByTestId,
} = renderIntoDocument(`
<div>
<input placeholder="name" type="text" data-testid="name" value="Mercury" />
</div>
`);
expect(getByDisplayValue('Mercury').placeholder).toEqual('name');
expect(queryByDisplayValue('Mercury').placeholder).toEqual('name');
getByTestId('name').value = 'Norris';
expect(getByDisplayValue('Norris').placeholder).toEqual('name');
expect(queryByDisplayValue('Norris').placeholder).toEqual('name');
expect(queryByDisplayValue('Nor', {
exact: false
}).placeholder).toEqual('name');
});
`)
expect(getByDisplayValue('Mercury').placeholder).toEqual('name')
expect(queryByDisplayValue('Mercury').placeholder).toEqual('name')
getByTestId('name').value = 'Norris'
expect(getByDisplayValue('Norris').placeholder).toEqual('name')
expect(queryByDisplayValue('Norris').placeholder).toEqual('name')
expect(queryByDisplayValue('Nor', {exact: false}).placeholder).toEqual('name')
})
test('get/query select element by current value', () => {

@@ -707,4 +741,4 @@ const {

queryByDisplayValue,
getByTestId
} = (0, _testUtils.renderIntoDocument)(`
getByTestId,
} = renderIntoDocument(`
<select id="state-select" data-testid="state">

@@ -716,9 +750,12 @@ <option value="">State</option>

</select>
`);
expect(getByDisplayValue('Alaska').id).toEqual('state-select');
expect(queryByDisplayValue('Alaska').id).toEqual('state-select');
getByTestId('state').value = 'AL';
expect(getByDisplayValue('Alabama').id).toEqual('state-select');
expect(queryByDisplayValue('Alabama').id).toEqual('state-select');
});
`)
expect(getByDisplayValue('Alaska').id).toEqual('state-select')
expect(queryByDisplayValue('Alaska').id).toEqual('state-select')
getByTestId('state').value = 'AL'
expect(getByDisplayValue('Alabama').id).toEqual('state-select')
expect(queryByDisplayValue('Alabama').id).toEqual('state-select')
})
test('get/query textarea element by current value', () => {

@@ -728,14 +765,17 @@ const {

queryByDisplayValue,
getByTestId
} = (0, _testUtils.renderIntoDocument)(`
getByTestId,
} = renderIntoDocument(`
<textarea id="content-textarea" data-testid="content">
Hello
</textarea>
`);
expect(getByDisplayValue('Hello').id).toEqual('content-textarea');
expect(queryByDisplayValue('Hello').id).toEqual('content-textarea');
getByTestId('content').value = 'World';
expect(getByDisplayValue('World').id).toEqual('content-textarea');
expect(queryByDisplayValue('World').id).toEqual('content-textarea');
});
/* eslint jsx-a11y/label-has-for:0 */
`)
expect(getByDisplayValue('Hello').id).toEqual('content-textarea')
expect(queryByDisplayValue('Hello').id).toEqual('content-textarea')
getByTestId('content').value = 'World'
expect(getByDisplayValue('World').id).toEqual('content-textarea')
expect(queryByDisplayValue('World').id).toEqual('content-textarea')
})
/* eslint jsx-a11y/label-has-for:0 */

@@ -1,156 +0,195 @@

"use strict";
import {fireEvent} from '..'
var _ = require("..");
const eventTypes = [
{
type: 'Clipboard',
events: ['copy', 'paste'],
elementType: 'input',
},
{
type: 'Composition',
events: ['compositionEnd', 'compositionStart', 'compositionUpdate'],
elementType: 'input',
},
{
type: 'Keyboard',
events: ['keyDown', 'keyPress', 'keyUp'],
elementType: 'input',
},
{
type: 'Focus',
events: ['focus', 'blur', 'focusIn', 'focusOut'],
elementType: 'input',
},
{
type: 'Form',
events: ['focus', 'blur'],
elementType: 'input',
},
{
type: 'Focus',
events: ['change', 'input', 'invalid'],
elementType: 'input',
},
{
type: 'Focus',
events: ['submit'],
elementType: 'form',
},
{
type: 'Mouse',
events: [
'click',
'contextMenu',
'dblClick',
'drag',
'dragEnd',
'dragEnter',
'dragExit',
'dragLeave',
'dragOver',
'dragStart',
'drop',
'mouseDown',
'mouseEnter',
'mouseLeave',
'mouseMove',
'mouseOut',
'mouseOver',
'mouseUp',
],
elementType: 'button',
},
{
type: 'Selection',
events: ['select'],
elementType: 'input',
},
{
type: 'Touch',
events: ['touchCancel', 'touchEnd', 'touchMove', 'touchStart'],
elementType: 'button',
},
{
type: 'UI',
events: ['scroll'],
elementType: 'div',
},
{
type: 'Wheel',
events: ['wheel'],
elementType: 'div',
},
{
type: 'Media',
events: [
'abort',
'canPlay',
'canPlayThrough',
'durationChange',
'emptied',
'encrypted',
'ended',
'error',
'loadedData',
'loadedMetadata',
'loadStart',
'pause',
'play',
'playing',
'progress',
'rateChange',
'seeked',
'seeking',
'stalled',
'suspend',
'timeUpdate',
'volumeChange',
'waiting',
],
elementType: 'video',
},
{
type: 'Image',
events: ['load', 'error'],
elementType: 'img',
},
{
type: 'Animation',
events: ['animationStart', 'animationEnd', 'animationIteration'],
elementType: 'div',
},
{
type: 'Transition',
events: ['transitionEnd'],
elementType: 'div',
},
]
const eventTypes = [{
type: 'Clipboard',
events: ['copy', 'paste'],
elementType: 'input'
}, {
type: 'Composition',
events: ['compositionEnd', 'compositionStart', 'compositionUpdate'],
elementType: 'input'
}, {
type: 'Keyboard',
events: ['keyDown', 'keyPress', 'keyUp'],
elementType: 'input'
}, {
type: 'Focus',
events: ['focus', 'blur', 'focusIn', 'focusOut'],
elementType: 'input'
}, {
type: 'Form',
events: ['focus', 'blur'],
elementType: 'input'
}, {
type: 'Focus',
events: ['change', 'input', 'invalid'],
elementType: 'input'
}, {
type: 'Focus',
events: ['submit'],
elementType: 'form'
}, {
type: 'Mouse',
events: ['click', 'contextMenu', 'dblClick', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'mouseDown', 'mouseEnter', 'mouseLeave', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp'],
elementType: 'button'
}, {
type: 'Selection',
events: ['select'],
elementType: 'input'
}, {
type: 'Touch',
events: ['touchCancel', 'touchEnd', 'touchMove', 'touchStart'],
elementType: 'button'
}, {
type: 'UI',
events: ['scroll'],
elementType: 'div'
}, {
type: 'Wheel',
events: ['wheel'],
elementType: 'div'
}, {
type: 'Media',
events: ['abort', 'canPlay', 'canPlayThrough', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'loadedData', 'loadedMetadata', 'loadStart', 'pause', 'play', 'playing', 'progress', 'rateChange', 'seeked', 'seeking', 'stalled', 'suspend', 'timeUpdate', 'volumeChange', 'waiting'],
elementType: 'video'
}, {
type: 'Image',
events: ['load', 'error'],
elementType: 'img'
}, {
type: 'Animation',
events: ['animationStart', 'animationEnd', 'animationIteration'],
elementType: 'div'
}, {
type: 'Transition',
events: ['transitionEnd'],
elementType: 'div'
}];
eventTypes.forEach(({
type,
events,
elementType
}) => {
eventTypes.forEach(({type, events, elementType}) => {
describe(`${type} Events`, () => {
events.forEach(eventName => {
it(`fires ${eventName}`, () => {
const node = document.createElement(elementType);
const spy = jest.fn();
node.addEventListener(eventName.toLowerCase(), spy);
const node = document.createElement(elementType)
const spy = jest.fn()
node.addEventListener(eventName.toLowerCase(), spy)
fireEvent[eventName](node)
expect(spy).toHaveBeenCalledTimes(1)
})
})
})
})
_.fireEvent[eventName](node);
expect(spy).toHaveBeenCalledTimes(1);
});
});
});
});
describe(`Aliased Events`, () => {
it(`fires doubleClick`, () => {
const node = document.createElement('div');
const spy = jest.fn();
node.addEventListener('dblclick', spy);
const node = document.createElement('div')
const spy = jest.fn()
node.addEventListener('dblclick', spy)
fireEvent.doubleClick(node)
expect(spy).toHaveBeenCalledTimes(1)
})
})
_.fireEvent.doubleClick(node);
expect(spy).toHaveBeenCalledTimes(1);
});
});
test('assigns target properties', () => {
const node = document.createElement('input');
const spy = jest.fn();
const value = 'a';
node.addEventListener('change', spy);
const node = document.createElement('input')
const spy = jest.fn()
const value = 'a'
node.addEventListener('change', spy)
fireEvent.change(node, {target: {value}})
expect(spy).toHaveBeenCalledTimes(1)
expect(node.value).toBe(value)
})
_.fireEvent.change(node, {
target: {
value
}
});
test('assigning a value to a target that cannot have a value throws an error', () => {
const node = document.createElement('div')
expect(() =>
fireEvent.change(node, {target: {value: 'a'}}),
).toThrowErrorMatchingInlineSnapshot(
`"The given element does not have a value setter"`,
)
})
expect(spy).toHaveBeenCalledTimes(1);
expect(node.value).toBe(value);
});
test('assigning a value to a target that cannot have a value throws an error', () => {
const node = document.createElement('div');
expect(() => _.fireEvent.change(node, {
target: {
value: 'a'
}
})).toThrowErrorMatchingInlineSnapshot(`"The given element does not have a value setter"`);
});
test('assigning the files property on an input', () => {
const node = document.createElement('input');
const node = document.createElement('input')
const file = new document.defaultView.File(['(⌐□_□)'], 'chucknorris.png', {
type: 'image/png'
});
type: 'image/png',
})
fireEvent.change(node, {target: {files: [file]}})
expect(node.files).toEqual([file])
})
_.fireEvent.change(node, {
target: {
files: [file]
}
});
test('fires events on Window', () => {
const messageSpy = jest.fn()
window.addEventListener('message', messageSpy)
fireEvent(window, new window.MessageEvent('message', {data: 'hello'}))
expect(messageSpy).toHaveBeenCalledTimes(1)
window.removeEventListener('message', messageSpy)
})
expect(node.files).toEqual([file]);
});
test('fires events on Window', () => {
const messageSpy = jest.fn();
window.addEventListener('message', messageSpy);
(0, _.fireEvent)(window, new window.MessageEvent('message', {
data: 'hello'
}));
expect(messageSpy).toHaveBeenCalledTimes(1);
window.removeEventListener('message', messageSpy);
});
test('fires events on Document', () => {
const keyDownSpy = jest.fn();
document.addEventListener('keydown', keyDownSpy);
_.fireEvent.keyDown(document, {
key: 'Escape'
});
expect(keyDownSpy).toHaveBeenCalledTimes(1);
document.removeEventListener('keydown', keyDownSpy);
});
const keyDownSpy = jest.fn()
document.addEventListener('keydown', keyDownSpy)
fireEvent.keyDown(document, {key: 'Escape'})
expect(keyDownSpy).toHaveBeenCalledTimes(1)
document.removeEventListener('keydown', keyDownSpy)
})

@@ -1,6 +0,11 @@

"use strict";
// query utilities:
import {
getByLabelText,
getByText,
getByTestId,
queryByTestId,
wait,
fireEvent,
} from '../'
var _ = require("../");
// query utilities:
function getExampleDOM() {

@@ -10,3 +15,3 @@ // This is just a raw example of setting up some DOM

// framework of choice 😉
const div = document.createElement('div');
const div = document.createElement('div')
div.innerHTML = `

@@ -16,5 +21,5 @@ <label for="username">Username</label>

<button>Print Username</button>
`;
const button = div.querySelector('button');
const input = div.querySelector('input');
`
const button = div.querySelector('button')
const input = div.querySelector('input')
button.addEventListener('click', () => {

@@ -24,31 +29,33 @@ // let's pretend this is making a server request, so it's async

setTimeout(() => {
const printedUsernameContainer = document.createElement('div');
const printedUsernameContainer = document.createElement('div')
printedUsernameContainer.innerHTML = `
<div data-testid="printed-username">${input.value}</div>
`;
div.appendChild(printedUsernameContainer);
}, Math.floor(Math.random() * 200));
});
return div;
`
div.appendChild(printedUsernameContainer)
}, Math.floor(Math.random() * 200))
})
return div
}
test('examples of some things', async () => {
const famousWomanInHistory = 'Ada Lovelace';
const container = getExampleDOM(); // Get form elements by their label text.
const famousWomanInHistory = 'Ada Lovelace'
const container = getExampleDOM()
// Get form elements by their label text.
// An error will be thrown if one cannot be found (accessibility FTW!)
const input = getByLabelText(container, 'Username')
fireEvent.change(input, {target: {value: famousWomanInHistory}})
const input = (0, _.getByLabelText)(container, 'Username');
// Get elements by their text, just like a real user does.
getByText(container, 'Print Username').click()
_.fireEvent.change(input, {
target: {
value: famousWomanInHistory
}
}); // Get elements by their text, just like a real user does.
await wait(() =>
expect(queryByTestId(container, 'printed-username')).toBeTruthy(),
)
(0, _.getByText)(container, 'Print Username').click();
await (0, _.wait)(() => expect((0, _.queryByTestId)(container, 'printed-username')).toBeTruthy()); // getByTestId and queryByTestId are an escape hatch to get elements
// getByTestId and queryByTestId are an escape hatch to get elements
// by a test id (could also attempt to get this element by it's text)
expect((0, _.getByTestId)(container, 'printed-username')).toHaveTextContent(famousWomanInHistory);
expect(getByTestId(container, 'printed-username')).toHaveTextContent(
famousWomanInHistory,
)
expect(container).toMatchInlineSnapshot(`

@@ -87,3 +94,3 @@ <div>

</div>
`);
});
`)
})

@@ -1,34 +0,31 @@

"use strict";
import {getQueriesForElement} from '../get-queries-for-element'
import {queries} from '..'
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
test('uses default queries', () => {
const container = document.createElement('div')
const boundQueries = getQueriesForElement(container)
expect(Object.keys(boundQueries)).toEqual(Object.keys(queries))
})
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
test('accepts custom queries', () => {
const container = document.createElement('div')
const customQuery = jest.fn()
const boundQueries = getQueriesForElement(container, {
...queries,
customQuery,
})
expect(boundQueries.customQuery).toBeDefined()
})
var _getQueriesForElement = require("../get-queries-for-element");
var _ = require("..");
test('uses default queries', () => {
const container = document.createElement('div');
const boundQueries = (0, _getQueriesForElement.getQueriesForElement)(container);
expect(Object.keys(boundQueries)).toEqual(Object.keys(_.queries));
});
test('accepts custom queries', () => {
const container = document.createElement('div');
const customQuery = jest.fn();
const boundQueries = (0, _getQueriesForElement.getQueriesForElement)(container, (0, _extends2.default)({}, _.queries, {
customQuery
}));
expect(boundQueries.customQuery).toBeDefined();
});
test('binds functions to container', () => {
const container = document.createElement('div');
const mock = jest.fn();
const boundQueries = (0, _getQueriesForElement.getQueriesForElement)(container, {
customQuery: function (element) {
return mock(element);
}
});
boundQueries.customQuery();
expect(mock).toHaveBeenCalledWith(container);
});
const container = document.createElement('div')
const mock = jest.fn()
function customQuery(element) {
return mock(element)
}
const boundQueries = getQueriesForElement(container, {
customQuery,
})
boundQueries.customQuery()
expect(mock).toHaveBeenCalledWith(container)
})

@@ -1,14 +0,11 @@

"use strict";
import {getDocument, newMutationObserver} from '../helpers'
var _helpers = require("../helpers");
test('returns global document if exists', () => {
expect((0, _helpers.getDocument)()).toBe(document);
});
expect(getDocument()).toBe(document)
})
class DummyClass {
constructor(args) {
this.args = args;
this.args = args
}
}

@@ -19,16 +16,16 @@

it('instantiates mock MutationObserver if not availble on window', () => {
expect((0, _helpers.newMutationObserver)(() => {}).observe).toBeDefined();
});
expect(newMutationObserver(() => {}).observe).toBeDefined()
})
} else {
it('instantiates from global MutationObserver if available', () => {
const oldMutationObserver = window.MutationObserver;
window.MutationObserver = DummyClass;
const oldMutationObserver = window.MutationObserver
window.MutationObserver = DummyClass
try {
expect((0, _helpers.newMutationObserver)('foobar').args).toEqual('foobar');
expect(newMutationObserver('foobar').args).toEqual('foobar')
} finally {
window.MutationObserver = oldMutationObserver;
window.MutationObserver = oldMutationObserver
}
});
})
}
});
})

@@ -1,39 +0,20 @@

"use strict";
import {getQueriesForElement} from '../../get-queries-for-element'
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.render = render;
exports.renderIntoDocument = renderIntoDocument;
exports.cleanup = cleanup;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _getQueriesForElement = require("../../get-queries-for-element");
function render(html, {
container = document.createElement('div')
} = {}) {
container.innerHTML = html;
const containerQueries = (0, _getQueriesForElement.getQueriesForElement)(container);
return (0, _extends2.default)({
container,
rerender: function (newHtml) {
return render(newHtml, {
container
});
}
}, containerQueries);
function render(html, {container = document.createElement('div')} = {}) {
container.innerHTML = html
const containerQueries = getQueriesForElement(container)
function rerender(newHtml) {
return render(newHtml, {container})
}
return {container, rerender, ...containerQueries}
}
function renderIntoDocument(html) {
return render(html, {
container: document.body
});
return render(html, {container: document.body})
}
function cleanup() {
document.body.innerHTML = '';
}
document.body.innerHTML = ''
}
export {render, renderIntoDocument, cleanup}

@@ -1,25 +0,28 @@

"use strict";
import {fuzzyMatches, matches} from '../matches'
var _matches = require("../matches");
// unit tests for text match utils
const node = null;
const normalizer = str => str;
const node = null
const normalizer = str => str
test('matchers accept strings', () => {
expect((0, _matches.matches)('ABC', node, 'ABC', normalizer)).toBe(true);
expect((0, _matches.fuzzyMatches)('ABC', node, 'ABC', normalizer)).toBe(true);
});
expect(matches('ABC', node, 'ABC', normalizer)).toBe(true)
expect(fuzzyMatches('ABC', node, 'ABC', normalizer)).toBe(true)
})
test('matchers accept regex', () => {
expect((0, _matches.matches)('ABC', node, /ABC/, normalizer)).toBe(true);
expect((0, _matches.fuzzyMatches)('ABC', node, /ABC/, normalizer)).toBe(true);
});
expect(matches('ABC', node, /ABC/, normalizer)).toBe(true)
expect(fuzzyMatches('ABC', node, /ABC/, normalizer)).toBe(true)
})
test('matchers accept functions', () => {
expect((0, _matches.matches)('ABC', node, text => text === 'ABC', normalizer)).toBe(true);
expect((0, _matches.fuzzyMatches)('ABC', node, text => text === 'ABC', normalizer)).toBe(true);
});
expect(matches('ABC', node, text => text === 'ABC', normalizer)).toBe(true)
expect(fuzzyMatches('ABC', node, text => text === 'ABC', normalizer)).toBe(
true,
)
})
test('matchers return false if text to match is not a string', () => {
expect((0, _matches.matches)(null, node, 'ABC', normalizer)).toBe(false);
expect((0, _matches.fuzzyMatches)(null, node, 'ABC', normalizer)).toBe(false);
});
expect(matches(null, node, 'ABC', normalizer)).toBe(false)
expect(fuzzyMatches(null, node, 'ABC', normalizer)).toBe(false)
})

@@ -1,12 +0,7 @@

"use strict";
import {prettyDOM} from '../pretty-dom'
import {render} from './helpers/test-utils'
var _prettyDom = require("../pretty-dom");
var _testUtils = require("./helpers/test-utils");
test('it prints out the given DOM element tree', () => {
const {
container
} = (0, _testUtils.render)('<div>Hello World!</div>');
expect((0, _prettyDom.prettyDOM)(container)).toMatchInlineSnapshot(`
const {container} = render('<div>Hello World!</div>')
expect(prettyDOM(container)).toMatchInlineSnapshot(`
"<div>

@@ -17,12 +12,12 @@ <div>

</div>"
`);
});
`)
})
test('it supports truncating the output length', () => {
const {
container
} = (0, _testUtils.render)('<div>Hello World!</div>');
expect((0, _prettyDom.prettyDOM)(container, 5)).toMatch(/\.\.\./);
});
const {container} = render('<div>Hello World!</div>')
expect(prettyDOM(container, 5)).toMatch(/\.\.\./)
})
test('it supports receiving the document element', () => {
expect((0, _prettyDom.prettyDOM)(document)).toMatchInlineSnapshot(`
expect(prettyDOM(document)).toMatchInlineSnapshot(`
"<html>

@@ -32,3 +27,3 @@ <head />

</html>"
`);
});
`)
})

@@ -1,5 +0,3 @@

"use strict";
import {render} from './helpers/test-utils'
var _testUtils = require("./helpers/test-utils");
test('find asynchronously finds elements', async () => {

@@ -9,17 +7,24 @@ const {

findAllByLabelText,
findByPlaceholderText,
findAllByPlaceholderText,
findByText,
findAllByText,
findByAltText,
findAllByAltText,
findByTitle,
findAllByTitle,
findByDisplayValue,
findAllByDisplayValue,
findByRole,
findAllByRole,
findByTestId,
findAllByTestId
} = (0, _testUtils.render)(`
findAllByTestId,
} = render(`
<div>

@@ -33,20 +38,28 @@ <div data-testid="test-id" aria-label="test-label">test text content</div>

</div>
`);
await expect(findByLabelText('test-label')).resolves.toBeTruthy();
await expect(findAllByLabelText('test-label')).resolves.toHaveLength(1);
await expect(findByPlaceholderText('placeholder')).resolves.toBeTruthy();
await expect(findAllByPlaceholderText('placeholder')).resolves.toHaveLength(1);
await expect(findByText('test text content')).resolves.toBeTruthy();
await expect(findAllByText('test text content')).resolves.toHaveLength(1);
await expect(findByAltText('test alt text')).resolves.toBeTruthy();
await expect(findAllByAltText('test alt text')).resolves.toHaveLength(1);
await expect(findByTitle('test title')).resolves.toBeTruthy();
await expect(findAllByTitle('test title')).resolves.toHaveLength(1);
await expect(findByDisplayValue('display value')).resolves.toBeTruthy();
await expect(findAllByDisplayValue('display value')).resolves.toHaveLength(1);
await expect(findByRole('dialog')).resolves.toBeTruthy();
await expect(findAllByRole('dialog')).resolves.toHaveLength(1);
await expect(findByTestId('test-id')).resolves.toBeTruthy();
await expect(findAllByTestId('test-id')).resolves.toHaveLength(1);
});
`)
await expect(findByLabelText('test-label')).resolves.toBeTruthy()
await expect(findAllByLabelText('test-label')).resolves.toHaveLength(1)
await expect(findByPlaceholderText('placeholder')).resolves.toBeTruthy()
await expect(findAllByPlaceholderText('placeholder')).resolves.toHaveLength(1)
await expect(findByText('test text content')).resolves.toBeTruthy()
await expect(findAllByText('test text content')).resolves.toHaveLength(1)
await expect(findByAltText('test alt text')).resolves.toBeTruthy()
await expect(findAllByAltText('test alt text')).resolves.toHaveLength(1)
await expect(findByTitle('test title')).resolves.toBeTruthy()
await expect(findAllByTitle('test title')).resolves.toHaveLength(1)
await expect(findByDisplayValue('display value')).resolves.toBeTruthy()
await expect(findAllByDisplayValue('display value')).resolves.toHaveLength(1)
await expect(findByRole('dialog')).resolves.toBeTruthy()
await expect(findAllByRole('dialog')).resolves.toHaveLength(1)
await expect(findByTestId('test-id')).resolves.toBeTruthy()
await expect(findAllByTestId('test-id')).resolves.toHaveLength(1)
})
test('find rejects when something cannot be found', async () => {

@@ -56,53 +69,60 @@ const {

findAllByLabelText,
findByPlaceholderText,
findAllByPlaceholderText,
findByText,
findAllByText,
findByAltText,
findAllByAltText,
findByTitle,
findAllByTitle,
findByDisplayValue,
findAllByDisplayValue,
findByRole,
findAllByRole,
findByTestId,
findAllByTestId
} = (0, _testUtils.render)(`<div />`); // I just don't want multiple lines for these.
findAllByTestId,
} = render(`<div />`)
// I just don't want multiple lines for these.
// qo = queryOptions
// wo = waitForElementOptions
const qo = {} // query options
const wo = {timeout: 10} // wait options
const qo = {}; // query options
await expect(findByLabelText('x', qo, wo)).rejects.toThrow('x')
await expect(findAllByLabelText('x', qo, wo)).rejects.toThrow('x')
const wo = {
timeout: 10 // wait options
await expect(findByPlaceholderText('x', qo, wo)).rejects.toThrow('x')
await expect(findAllByPlaceholderText('x', qo, wo)).rejects.toThrow('x')
};
await expect(findByLabelText('x', qo, wo)).rejects.toThrow('x');
await expect(findAllByLabelText('x', qo, wo)).rejects.toThrow('x');
await expect(findByPlaceholderText('x', qo, wo)).rejects.toThrow('x');
await expect(findAllByPlaceholderText('x', qo, wo)).rejects.toThrow('x');
await expect(findByText('x', qo, wo)).rejects.toThrow('x');
await expect(findAllByText('x', qo, wo)).rejects.toThrow('x');
await expect(findByAltText('x', qo, wo)).rejects.toThrow('x');
await expect(findAllByAltText('x', qo, wo)).rejects.toThrow('x');
await expect(findByTitle('x', qo, wo)).rejects.toThrow('x');
await expect(findAllByTitle('x', qo, wo)).rejects.toThrow('x');
await expect(findByDisplayValue('x', qo, wo)).rejects.toThrow('x');
await expect(findAllByDisplayValue('x', qo, wo)).rejects.toThrow('x');
await expect(findByRole('x', qo, wo)).rejects.toThrow('x');
await expect(findAllByRole('x', qo, wo)).rejects.toThrow('x');
await expect(findByTestId('x', qo, wo)).rejects.toThrow('x');
await expect(findAllByTestId('x', qo, wo)).rejects.toThrow('x');
});
await expect(findByText('x', qo, wo)).rejects.toThrow('x')
await expect(findAllByText('x', qo, wo)).rejects.toThrow('x')
await expect(findByAltText('x', qo, wo)).rejects.toThrow('x')
await expect(findAllByAltText('x', qo, wo)).rejects.toThrow('x')
await expect(findByTitle('x', qo, wo)).rejects.toThrow('x')
await expect(findAllByTitle('x', qo, wo)).rejects.toThrow('x')
await expect(findByDisplayValue('x', qo, wo)).rejects.toThrow('x')
await expect(findAllByDisplayValue('x', qo, wo)).rejects.toThrow('x')
await expect(findByRole('x', qo, wo)).rejects.toThrow('x')
await expect(findAllByRole('x', qo, wo)).rejects.toThrow('x')
await expect(findByTestId('x', qo, wo)).rejects.toThrow('x')
await expect(findAllByTestId('x', qo, wo)).rejects.toThrow('x')
})
test('actually works with async code', async () => {
const {
findByTestId,
container,
rerender
} = (0, _testUtils.render)(`<div />`);
setTimeout(() => rerender(`<div data-testid="div">correct dom</div>`), 20);
await expect(findByTestId('div', {}, {
container
})).resolves.toBeTruthy();
});
const {findByTestId, container, rerender} = render(`<div />`)
setTimeout(() => rerender(`<div data-testid="div">correct dom</div>`), 20)
await expect(findByTestId('div', {}, {container})).resolves.toBeTruthy()
})

@@ -1,32 +0,30 @@

"use strict";
import cases from 'jest-in-case'
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
import {getDefaultNormalizer} from '../'
import {render} from './helpers/test-utils'
var _jestInCase = _interopRequireDefault(require("jest-in-case"));
cases(
'matches find case-sensitive full strings by default',
({dom, query, queryFn}) => {
const queries = render(dom)
var _ = require("../");
const queryString = query
const queryRegex = new RegExp(query)
const queryFunc = text => text === query
var _testUtils = require("./helpers/test-utils");
expect(queries[queryFn](queryString)).toHaveLength(1)
expect(queries[queryFn](queryRegex)).toHaveLength(1)
expect(queries[queryFn](queryFunc)).toHaveLength(1)
(0, _jestInCase.default)('matches find case-sensitive full strings by default', ({
dom,
query,
queryFn
}) => {
const queries = (0, _testUtils.render)(dom);
const queryRegex = new RegExp(query);
expect(queries[queryFn](query)).toHaveLength(1);
expect(queries[queryFn](queryRegex)).toHaveLength(1);
expect(queries[queryFn](text => text === query)).toHaveLength(1);
expect(queries[queryFn](query.toUpperCase())).toHaveLength(0); // case
expect(queries[queryFn](query.slice(0, 1))).toHaveLength(0); // substring
}, {
queryAllByTestId: {
dom: `<a data-testid="link" href="#">Link</a>`,
query: `link`,
queryFn: `queryAllByTestId`
expect(queries[queryFn](query.toUpperCase())).toHaveLength(0) // case
expect(queries[queryFn](query.slice(0, 1))).toHaveLength(0) // substring
},
queryAllByAltText: {
dom: `
{
queryAllByTestId: {
dom: `<a data-testid="link" href="#">Link</a>`,
query: `link`,
queryFn: `queryAllByTestId`,
},
queryAllByAltText: {
dom: `
<img

@@ -36,12 +34,12 @@ alt="Finding Nemo poster"

/>`,
query: `Finding Nemo poster`,
queryFn: `queryAllByAltText`
},
queryAllByPlaceholderText: {
dom: `<input placeholder="Dwayne 'The Rock' Johnson" />`,
query: `Dwayne 'The Rock' Johnson`,
queryFn: `queryAllByPlaceholderText`
},
queryAllBySelectText: {
dom: `
query: `Finding Nemo poster`,
queryFn: `queryAllByAltText`,
},
queryAllByPlaceholderText: {
dom: `<input placeholder="Dwayne 'The Rock' Johnson" />`,
query: `Dwayne 'The Rock' Johnson`,
queryFn: `queryAllByPlaceholderText`,
},
queryAllBySelectText: {
dom: `
<select>

@@ -51,39 +49,42 @@ <option>Option 1</option>

</select>`,
query: `Option 1`,
queryFn: `queryAllBySelectText`
},
queryAllByText: {
dom: `<p>Some content</p>`,
query: `Some content`,
queryFn: `queryAllByText`
},
queryAllByLabelText: {
dom: `
query: `Option 1`,
queryFn: `queryAllBySelectText`,
},
queryAllByText: {
dom: `<p>Some content</p>`,
query: `Some content`,
queryFn: `queryAllByText`,
},
queryAllByLabelText: {
dom: `
<label for="username">User Name</label>
<input id="username" />`,
query: `User Name`,
queryFn: `queryAllByLabelText`
}
});
(0, _jestInCase.default)('queries trim leading, trailing & inner whitespace by default', ({
dom,
query,
queryFn
}) => {
const queries = (0, _testUtils.render)(dom);
expect(queries[queryFn](query)).toHaveLength(1);
expect(queries[queryFn](query, {
normalizer: (0, _.getDefaultNormalizer)({
collapseWhitespace: false,
trim: false
})
})).toHaveLength(0);
}, {
queryAllByTestId: {
dom: `<a data-testid=" link " href="#">Link</a>`,
query: /^link$/,
queryFn: `queryAllByTestId`
query: `User Name`,
queryFn: `queryAllByLabelText`,
},
},
queryAllByAltText: {
dom: `
)
cases(
'queries trim leading, trailing & inner whitespace by default',
({dom, query, queryFn}) => {
const queries = render(dom)
expect(queries[queryFn](query)).toHaveLength(1)
expect(
queries[queryFn](query, {
normalizer: getDefaultNormalizer({
collapseWhitespace: false,
trim: false,
}),
}),
).toHaveLength(0)
},
{
queryAllByTestId: {
dom: `<a data-testid=" link " href="#">Link</a>`,
query: /^link$/,
queryFn: `queryAllByTestId`,
},
queryAllByAltText: {
dom: `
<img

@@ -94,13 +95,13 @@ alt="

/>`,
query: /^Finding Nemo poster$/,
queryFn: `queryAllByAltText`
},
queryAllByPlaceholderText: {
dom: `
query: /^Finding Nemo poster$/,
queryFn: `queryAllByAltText`,
},
queryAllByPlaceholderText: {
dom: `
<input placeholder=" Dwayne 'The Rock' Johnson " />`,
query: /^Dwayne/,
queryFn: `queryAllByPlaceholderText`
},
queryAllBySelectText: {
dom: `
query: /^Dwayne/,
queryFn: `queryAllByPlaceholderText`,
},
queryAllBySelectText: {
dom: `
<select>

@@ -110,7 +111,7 @@ <option> Option 1 </option>

</select>`,
query: `Option 1`,
queryFn: `queryAllBySelectText`
},
queryAllByText: {
dom: `
query: `Option 1`,
queryFn: `queryAllBySelectText`,
},
queryAllByText: {
dom: `
<p>

@@ -123,7 +124,7 @@ Content

</p>`,
query: `Content with linebreaks is ok`,
queryFn: `queryAllByText`
},
queryAllByLabelText: {
dom: `
query: `Content with linebreaks is ok`,
queryFn: `queryAllByText`,
},
queryAllByLabelText: {
dom: `
<label for="username">

@@ -134,37 +135,38 @@ User

<input id="username" />`,
query: `User Name`,
queryFn: `queryAllByLabelText`
}
});
(0, _jestInCase.default)('{ exact } option toggles case-insensitive partial matches', ({
dom,
query,
queryFn
}) => {
const queries = (0, _testUtils.render)(dom);
const queryRegex = new RegExp(query);
expect(queries[queryFn](query)).toHaveLength(1);
expect(queries[queryFn](query, {
exact: false
})).toHaveLength(1);
expect(queries[queryFn](queryRegex, {
exact: false
})).toHaveLength(1);
expect(queries[queryFn](text => text === query, {
exact: false
})).toHaveLength(1);
expect(queries[queryFn](query.split(' ')[0], {
exact: false
})).toHaveLength(1);
expect(queries[queryFn](query.toLowerCase(), {
exact: false
})).toHaveLength(1);
}, {
queryAllByPlaceholderText: {
dom: `<input placeholder="Dwayne 'The Rock' Johnson" />`,
query: `Dwayne 'The Rock' Johnson`,
queryFn: `queryAllByPlaceholderText`
query: `User Name`,
queryFn: `queryAllByLabelText`,
},
},
queryAllBySelectText: {
dom: `
)
cases(
'{ exact } option toggles case-insensitive partial matches',
({dom, query, queryFn}) => {
const queries = render(dom)
const queryString = query
const queryRegex = new RegExp(query)
const queryFunc = text => text === query
expect(queries[queryFn](query)).toHaveLength(1)
expect(queries[queryFn](queryString, {exact: false})).toHaveLength(1)
expect(queries[queryFn](queryRegex, {exact: false})).toHaveLength(1)
expect(queries[queryFn](queryFunc, {exact: false})).toHaveLength(1)
expect(queries[queryFn](query.split(' ')[0], {exact: false})).toHaveLength(
1,
)
expect(queries[queryFn](query.toLowerCase(), {exact: false})).toHaveLength(
1,
)
},
{
queryAllByPlaceholderText: {
dom: `<input placeholder="Dwayne 'The Rock' Johnson" />`,
query: `Dwayne 'The Rock' Johnson`,
queryFn: `queryAllByPlaceholderText`,
},
queryAllBySelectText: {
dom: `
<select>

@@ -174,14 +176,14 @@ <option>Option 1</option>

</select>`,
query: `Option 1`,
queryFn: `queryAllBySelectText`
},
queryAllByLabelText: {
dom: `
query: `Option 1`,
queryFn: `queryAllBySelectText`,
},
queryAllByLabelText: {
dom: `
<label for="username">User Name</label>
<input id="username" />`,
query: `User Name`,
queryFn: `queryAllByLabelText`
},
queryAllByText: {
dom: `
query: `User Name`,
queryFn: `queryAllByLabelText`,
},
queryAllByText: {
dom: `
<p>

@@ -194,7 +196,7 @@ Content

</p>`,
query: `Content with linebreaks is ok`,
queryFn: `queryAllByText`
},
queryAllByAltText: {
dom: `
query: `Content with linebreaks is ok`,
queryFn: `queryAllByText`,
},
queryAllByAltText: {
dom: `
<img

@@ -204,149 +206,131 @@ alt="Finding Nemo poster"

/>`,
query: `Finding Nemo poster`,
queryFn: `queryAllByAltText`
}
}); // A good use case for a custom normalizer is stripping
query: `Finding Nemo poster`,
queryFn: `queryAllByAltText`,
},
},
)
// A good use case for a custom normalizer is stripping
// out Unicode control characters such as LRM (left-right-mark)
// before matching
const LRM = '\u200e';
const LRM = '\u200e'
function removeUCC(str) {
return str.replace(/[\u200e]/g, '');
return str.replace(/[\u200e]/g, '')
}
(0, _jestInCase.default)('{ normalizer } option allows custom pre-match normalization', ({
dom,
queryFn
}) => {
const queries = (0, _testUtils.render)(dom);
const query = queries[queryFn]; // With the correct normalizer, we should match
cases(
'{ normalizer } option allows custom pre-match normalization',
({dom, queryFn}) => {
const queries = render(dom)
expect(query(/user n.me/i, {
normalizer: removeUCC
})).toHaveLength(1);
expect(query('User name', {
normalizer: removeUCC
})).toHaveLength(1); // Without the normalizer, we shouldn't
const query = queries[queryFn]
expect(query(/user n.me/i)).toHaveLength(0);
expect(query('User name')).toHaveLength(0);
}, {
queryAllByLabelText: {
dom: `
// With the correct normalizer, we should match
expect(query(/user n.me/i, {normalizer: removeUCC})).toHaveLength(1)
expect(query('User name', {normalizer: removeUCC})).toHaveLength(1)
// Without the normalizer, we shouldn't
expect(query(/user n.me/i)).toHaveLength(0)
expect(query('User name')).toHaveLength(0)
},
{
queryAllByLabelText: {
dom: `
<label for="username">User ${LRM}name</label>
<input id="username" />`,
queryFn: 'queryAllByLabelText'
queryFn: 'queryAllByLabelText',
},
queryAllByPlaceholderText: {
dom: `<input placeholder="User ${LRM}name" />`,
queryFn: 'queryAllByPlaceholderText',
},
queryAllBySelectText: {
dom: `<select><option>User ${LRM}name</option></select>`,
queryFn: 'queryAllBySelectText',
},
queryAllByText: {
dom: `<div>User ${LRM}name</div>`,
queryFn: 'queryAllByText',
},
queryAllByAltText: {
dom: `<img alt="User ${LRM}name" src="username.jpg" />`,
queryFn: 'queryAllByAltText',
},
queryAllByTitle: {
dom: `<div title="User ${LRM}name" />`,
queryFn: 'queryAllByTitle',
},
queryAllByValue: {
dom: `<input value="User ${LRM}name" />`,
queryFn: 'queryAllByValue',
},
queryAllByDisplayValue: {
dom: `<input value="User ${LRM}name" />`,
queryFn: 'queryAllByDisplayValue',
},
queryAllByRole: {
dom: `<input role="User ${LRM}name" />`,
queryFn: 'queryAllByRole',
},
},
queryAllByPlaceholderText: {
dom: `<input placeholder="User ${LRM}name" />`,
queryFn: 'queryAllByPlaceholderText'
},
queryAllBySelectText: {
dom: `<select><option>User ${LRM}name</option></select>`,
queryFn: 'queryAllBySelectText'
},
queryAllByText: {
dom: `<div>User ${LRM}name</div>`,
queryFn: 'queryAllByText'
},
queryAllByAltText: {
dom: `<img alt="User ${LRM}name" src="username.jpg" />`,
queryFn: 'queryAllByAltText'
},
queryAllByTitle: {
dom: `<div title="User ${LRM}name" />`,
queryFn: 'queryAllByTitle'
},
queryAllByValue: {
dom: `<input value="User ${LRM}name" />`,
queryFn: 'queryAllByValue'
},
queryAllByDisplayValue: {
dom: `<input value="User ${LRM}name" />`,
queryFn: 'queryAllByDisplayValue'
},
queryAllByRole: {
dom: `<input role="User ${LRM}name" />`,
queryFn: 'queryAllByRole'
}
});
)
test('normalizer works with both exact and non-exact matching', () => {
const {
queryAllByText
} = (0, _testUtils.render)(`<div>MiXeD ${LRM}CaSe</div>`);
expect(queryAllByText('mixed case', {
exact: false,
normalizer: removeUCC
})).toHaveLength(1);
expect(queryAllByText('mixed case', {
exact: true,
normalizer: removeUCC
})).toHaveLength(0);
expect(queryAllByText('MiXeD CaSe', {
exact: true,
normalizer: removeUCC
})).toHaveLength(1);
expect(queryAllByText('MiXeD CaSe', {
exact: true
})).toHaveLength(0);
});
const {queryAllByText} = render(`<div>MiXeD ${LRM}CaSe</div>`)
expect(
queryAllByText('mixed case', {exact: false, normalizer: removeUCC}),
).toHaveLength(1)
expect(
queryAllByText('mixed case', {exact: true, normalizer: removeUCC}),
).toHaveLength(0)
expect(
queryAllByText('MiXeD CaSe', {exact: true, normalizer: removeUCC}),
).toHaveLength(1)
expect(queryAllByText('MiXeD CaSe', {exact: true})).toHaveLength(0)
})
test('top-level trim and collapseWhitespace options are not supported if normalizer is specified', () => {
const {
queryAllByText
} = (0, _testUtils.render)('<div> abc def </div>');
const {queryAllByText} = render('<div> abc def </div>')
const normalizer = str => str
const normalizer = str => str;
expect(() => queryAllByText('abc', {trim: false, normalizer})).toThrow()
expect(() => queryAllByText('abc', {trim: true, normalizer})).toThrow()
expect(() =>
queryAllByText('abc', {collapseWhitespace: false, normalizer}),
).toThrow()
expect(() =>
queryAllByText('abc', {collapseWhitespace: true, normalizer}),
).toThrow()
})
expect(() => queryAllByText('abc', {
trim: false,
normalizer
})).toThrow();
expect(() => queryAllByText('abc', {
trim: true,
normalizer
})).toThrow();
expect(() => queryAllByText('abc', {
collapseWhitespace: false,
normalizer
})).toThrow();
expect(() => queryAllByText('abc', {
collapseWhitespace: true,
normalizer
})).toThrow();
});
test('getDefaultNormalizer returns a normalizer that supports trim and collapseWhitespace', () => {
// Default is trim: true and collapseWhitespace: true
expect((0, _.getDefaultNormalizer)()(' abc def ')).toEqual('abc def'); // Turning off trimming should not turn off whitespace collapsing
expect(getDefaultNormalizer()(' abc def ')).toEqual('abc def')
expect((0, _.getDefaultNormalizer)({
trim: false
})(' abc def ')).toEqual(' abc def '); // Turning off whitespace collapsing should not turn off trimming
// Turning off trimming should not turn off whitespace collapsing
expect(getDefaultNormalizer({trim: false})(' abc def ')).toEqual(
' abc def ',
)
expect((0, _.getDefaultNormalizer)({
collapseWhitespace: false
})(' abc def ')).toEqual('abc def'); // Whilst it's rather pointless, we should be able to turn both off
// Turning off whitespace collapsing should not turn off trimming
expect(
getDefaultNormalizer({collapseWhitespace: false})(' abc def '),
).toEqual('abc def')
expect((0, _.getDefaultNormalizer)({
trim: false,
collapseWhitespace: false
})(' abc def ')).toEqual(' abc def ');
});
// Whilst it's rather pointless, we should be able to turn both off
expect(
getDefaultNormalizer({trim: false, collapseWhitespace: false})(
' abc def ',
),
).toEqual(' abc def ')
})
test('we support an older API with trim and collapseWhitespace instead of a normalizer', () => {
const {
queryAllByText
} = (0, _testUtils.render)('<div> x y </div>');
expect(queryAllByText('x y')).toHaveLength(1);
expect(queryAllByText('x y', {
trim: false
})).toHaveLength(0);
expect(queryAllByText(' x y ', {
trim: false
})).toHaveLength(1);
expect(queryAllByText('x y', {
collapseWhitespace: false
})).toHaveLength(0);
expect(queryAllByText('x y', {
collapseWhitespace: false
})).toHaveLength(1);
});
const {queryAllByText} = render('<div> x y </div>')
expect(queryAllByText('x y')).toHaveLength(1)
expect(queryAllByText('x y', {trim: false})).toHaveLength(0)
expect(queryAllByText(' x y ', {trim: false})).toHaveLength(1)
expect(queryAllByText('x y', {collapseWhitespace: false})).toHaveLength(0)
expect(queryAllByText('x y', {collapseWhitespace: false})).toHaveLength(1)
})

@@ -1,15 +0,11 @@

"use strict";
import {waitForDomChange} from '../wait-for-dom-change'
import {renderIntoDocument, cleanup} from './helpers/test-utils'
var _waitForDomChange = require("../wait-for-dom-change");
afterEach(cleanup)
var _testUtils = require("./helpers/test-utils");
afterEach(_testUtils.cleanup);
test('waits for the dom to change in the document', async () => {
const {
container
} = (0, _testUtils.renderIntoDocument)('<div />');
const promise = (0, _waitForDomChange.waitForDomChange)();
setTimeout(() => container.firstChild.setAttribute('id', 'foo'));
const mutationResult = await promise;
const {container} = renderIntoDocument('<div />')
const promise = waitForDomChange()
setTimeout(() => container.firstChild.setAttribute('id', 'foo'))
const mutationResult = await promise
expect(mutationResult).toMatchInlineSnapshot(`

@@ -31,13 +27,10 @@ Array [

]
`);
});
`)
})
test('waits for the dom to change in a specified container', async () => {
const {
container
} = (0, _testUtils.renderIntoDocument)('<div />');
const promise = (0, _waitForDomChange.waitForDomChange)({
container
});
setTimeout(() => container.firstChild.setAttribute('id', 'foo'));
const mutationResult = await promise;
const {container} = renderIntoDocument('<div />')
const promise = waitForDomChange({container})
setTimeout(() => container.firstChild.setAttribute('id', 'foo'))
const mutationResult = await promise
expect(mutationResult).toMatchInlineSnapshot(`

@@ -59,27 +52,29 @@ Array [

]
`);
});
`)
})
test('can time out', async () => {
jest.useFakeTimers();
const promise = (0, _waitForDomChange.waitForDomChange)();
jest.advanceTimersByTime(4600);
await expect(promise).rejects.toThrow(/timed out/i);
jest.useRealTimers();
});
jest.useFakeTimers()
const promise = waitForDomChange()
jest.advanceTimersByTime(4600)
await expect(promise).rejects.toThrow(/timed out/i)
jest.useRealTimers()
})
test('can specify our own timeout time', async () => {
jest.useFakeTimers();
const promise = (0, _waitForDomChange.waitForDomChange)({
timeout: 4700
});
const handler = jest.fn();
promise.then(handler, handler); // advance beyond the default
jest.useFakeTimers()
const promise = waitForDomChange({timeout: 4700})
const handler = jest.fn()
promise.then(handler, handler)
// advance beyond the default
jest.advanceTimersByTime(4600)
// promise was neither rejected nor resolved
expect(handler).toHaveBeenCalledTimes(0)
jest.advanceTimersByTime(4600); // promise was neither rejected nor resolved
// advance beyond our specified timeout
jest.advanceTimersByTime(150)
expect(handler).toHaveBeenCalledTimes(0); // advance beyond our specified timeout
jest.advanceTimersByTime(150); // timed out
await expect(promise).rejects.toThrow(/timed out/i);
jest.useRealTimers();
});
// timed out
await expect(promise).rejects.toThrow(/timed out/i)
jest.useRealTimers()
})

@@ -1,24 +0,39 @@

"use strict";
import {waitForElementToBeRemoved} from '../'
import {render} from './helpers/test-utils'
var _ = require("../");
jest.useFakeTimers()
var _testUtils = require("./helpers/test-utils");
test('requires a function as the first parameter', () => {
return expect(
waitForElementToBeRemoved(),
).rejects.toThrowErrorMatchingInlineSnapshot(
`"waitForElementToBeRemoved requires a function as the first parameter"`,
)
})
jest.useFakeTimers();
test('requires a function as the first parameter', () => {
return expect((0, _.waitForElementToBeRemoved)()).rejects.toThrowErrorMatchingInlineSnapshot(`"waitForElementToBeRemoved requires a function as the first parameter"`);
});
test('requires an element to exist first', () => {
return expect((0, _.waitForElementToBeRemoved)(() => null)).rejects.toThrowErrorMatchingInlineSnapshot(`"The callback function which was passed did not return an element or non-empty array of elements. waitForElementToBeRemoved requires that the element(s) exist before waiting for removal."`);
});
return expect(
waitForElementToBeRemoved(() => null),
).rejects.toThrowErrorMatchingInlineSnapshot(
`"The callback function which was passed did not return an element or non-empty array of elements. waitForElementToBeRemoved requires that the element(s) exist before waiting for removal."`,
)
})
test('requires an unempty array of elements to exist first', () => {
return expect((0, _.waitForElementToBeRemoved)(() => [])).rejects.toThrowErrorMatchingInlineSnapshot(`"The callback function which was passed did not return an element or non-empty array of elements. waitForElementToBeRemoved requires that the element(s) exist before waiting for removal."`);
});
return expect(
waitForElementToBeRemoved(() => []),
).rejects.toThrowErrorMatchingInlineSnapshot(
`"The callback function which was passed did not return an element or non-empty array of elements. waitForElementToBeRemoved requires that the element(s) exist before waiting for removal."`,
)
})
test('times out after 4500ms by default', () => {
const {
container
} = (0, _testUtils.render)(`<div></div>`);
const promise = expect((0, _.waitForElementToBeRemoved)(() => container)).rejects.toThrowErrorMatchingInlineSnapshot(`"Timed out in waitForElementToBeRemoved."`);
jest.advanceTimersByTime(4501);
return promise;
});
const {container} = render(`<div></div>`)
const promise = expect(
waitForElementToBeRemoved(() => container),
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Timed out in waitForElementToBeRemoved."`,
)
jest.advanceTimersByTime(4501)
return promise
})

@@ -1,23 +0,19 @@

"use strict";
import {waitForElementToBeRemoved} from '../'
import {renderIntoDocument} from './helpers/test-utils'
var _ = require("../");
var _testUtils = require("./helpers/test-utils");
test('resolves on mutation only when the element is removed', async () => {
const {
queryAllByTestId
} = (0, _testUtils.renderIntoDocument)(`
const {queryAllByTestId} = renderIntoDocument(`
<div data-testid="div"></div>
<div data-testid="div"></div>
`);
const divs = queryAllByTestId('div'); // first mutation
`)
const divs = queryAllByTestId('div')
// first mutation
setTimeout(() => {
divs.forEach(d => d.setAttribute('id', 'mutated'));
}); // removal
divs.forEach(d => d.setAttribute('id', 'mutated'))
})
// removal
setTimeout(() => {
divs.forEach(div => div.parentElement.removeChild(div));
}, 100); // the timeout is here for two reasons:
divs.forEach(div => div.parentElement.removeChild(div))
}, 100)
// the timeout is here for two reasons:
// 1. It helps test the timeout config

@@ -27,20 +23,14 @@ // 2. The element should be removed immediately

// so we'll fail early and not wait the full timeout
await waitForElementToBeRemoved(() => queryAllByTestId('div'), {timeout: 200})
})
await (0, _.waitForElementToBeRemoved)(() => queryAllByTestId('div'), {
timeout: 200
});
});
test('resolves on mutation if callback throws an error', async () => {
const {
getByTestId
} = (0, _testUtils.renderIntoDocument)(`
const {getByTestId} = renderIntoDocument(`
<div data-testid="div"></div>
`);
const div = getByTestId('div');
`)
const div = getByTestId('div')
setTimeout(() => {
div.parentElement.removeChild(div);
});
await (0, _.waitForElementToBeRemoved)(() => getByTestId('div'), {
timeout: 100
});
});
div.parentElement.removeChild(div)
})
await waitForElementToBeRemoved(() => getByTestId('div'), {timeout: 100})
})

@@ -1,92 +0,78 @@

"use strict";
import {waitForElement} from '../wait-for-element'
import {render, renderIntoDocument, cleanup} from './helpers/test-utils'
var _waitForElement = require("../wait-for-element");
afterEach(cleanup)
var _testUtils = require("./helpers/test-utils");
test('waits for element to appear in the document', async () => {
const {rerender, getByTestId} = renderIntoDocument('<div />')
const promise = waitForElement(() => getByTestId('div'))
setTimeout(() => rerender('<div data-testid="div" />'))
const element = await promise
expect(element).toBeInTheDocument()
})
afterEach(_testUtils.cleanup);
test('waits for element to appear in the document', async () => {
const {
rerender,
getByTestId
} = (0, _testUtils.renderIntoDocument)('<div />');
const promise = (0, _waitForElement.waitForElement)(() => getByTestId('div'));
setTimeout(() => rerender('<div data-testid="div" />'));
const element = await promise;
expect(element).toBeInTheDocument();
});
test('waits for element to appear in a specified container', async () => {
const {
rerender,
container,
getByTestId
} = (0, _testUtils.render)('<div />');
const promise = (0, _waitForElement.waitForElement)(() => getByTestId('div'), {
container
});
setTimeout(() => rerender('<div data-testid="div" />'));
const element = await promise;
expect(element).toBeTruthy();
});
const {rerender, container, getByTestId} = render('<div />')
const promise = waitForElement(() => getByTestId('div'), {container})
setTimeout(() => rerender('<div data-testid="div" />'))
const element = await promise
expect(element).toBeTruthy()
})
test('can time out', async () => {
jest.useFakeTimers();
const promise = (0, _waitForElement.waitForElement)(() => {});
jest.advanceTimersByTime(4600);
await expect(promise).rejects.toThrow(/timed out/i);
jest.useRealTimers();
});
jest.useFakeTimers()
const promise = waitForElement(() => {})
jest.advanceTimersByTime(4600)
await expect(promise).rejects.toThrow(/timed out/i)
jest.useRealTimers()
})
test('can specify our own timeout time', async () => {
jest.useFakeTimers();
const promise = (0, _waitForElement.waitForElement)(() => {}, {
timeout: 4700
});
const handler = jest.fn();
promise.then(handler, handler); // advance beyond the default
jest.useFakeTimers()
const promise = waitForElement(() => {}, {timeout: 4700})
const handler = jest.fn()
promise.then(handler, handler)
// advance beyond the default
jest.advanceTimersByTime(4600)
// promise was neither rejected nor resolved
expect(handler).toHaveBeenCalledTimes(0)
jest.advanceTimersByTime(4600); // promise was neither rejected nor resolved
// advance beyond our specified timeout
jest.advanceTimersByTime(150)
expect(handler).toHaveBeenCalledTimes(0); // advance beyond our specified timeout
// timed out
await expect(promise).rejects.toThrow(/timed out/i)
jest.useRealTimers()
})
jest.advanceTimersByTime(150); // timed out
await expect(promise).rejects.toThrow(/timed out/i);
jest.useRealTimers();
});
test('throws last thrown error', async () => {
const {
rerender,
container
} = (0, _testUtils.render)('<div />');
let error;
const {rerender, container} = render('<div />')
let error
setTimeout(() => {
error = new Error('first error');
rerender('<div>first</div>');
}, 10);
error = new Error('first error')
rerender('<div>first</div>')
}, 10)
setTimeout(() => {
error = new Error('second error');
rerender('<div>second</div>');
}, 20);
const promise = (0, _waitForElement.waitForElement)(() => {
throw error;
}, {
container,
timeout: 50
});
await expect(promise).rejects.toThrow(error);
});
error = new Error('second error')
rerender('<div>second</div>')
}, 20)
const promise = waitForElement(
() => {
throw error
},
{container, timeout: 50},
)
await expect(promise).rejects.toThrow(error)
})
test('waits until callback does not return null', async () => {
const {
rerender,
container,
queryByTestId
} = (0, _testUtils.render)('<div />');
const promise = (0, _waitForElement.waitForElement)(() => queryByTestId('div'), {
container
});
setTimeout(() => rerender('<div data-testid="div" />'));
const element = await promise;
expect(element).toBeTruthy();
});
const {rerender, container, queryByTestId} = render('<div />')
const promise = waitForElement(() => queryByTestId('div'), {container})
setTimeout(() => rerender('<div data-testid="div" />'))
const element = await promise
expect(element).toBeTruthy()
})
test('throws error if no callback is provided', async () => {
await expect((0, _waitForElement.waitForElement)()).rejects.toThrow(/callback/i);
});
await expect(waitForElement()).rejects.toThrow(/callback/i)
})

@@ -1,19 +0,19 @@

"use strict";
import {wait} from '../'
var _ = require("../");
test('it waits for the data to be loaded', async () => {
const spy = jest.fn(); // we are using random timeout here to simulate a real-time example
const spy = jest.fn()
// we are using random timeout here to simulate a real-time example
// of an async operation calling a callback at a non-deterministic time
const randomTimeout = Math.floor(Math.random() * 60)
setTimeout(spy, randomTimeout)
const randomTimeout = Math.floor(Math.random() * 60);
setTimeout(spy, randomTimeout);
await (0, _.wait)(() => expect(spy).toHaveBeenCalledTimes(1));
expect(spy).toHaveBeenCalledWith();
});
await wait(() => expect(spy).toHaveBeenCalledTimes(1))
expect(spy).toHaveBeenCalledWith()
})
test('wait defaults to a noop callback', async () => {
const handler = jest.fn();
Promise.resolve().then(handler);
await (0, _.wait)();
expect(handler).toHaveBeenCalledTimes(1);
});
const handler = jest.fn()
Promise.resolve().then(handler)
await wait()
expect(handler).toHaveBeenCalledTimes(1)
})

@@ -17,3 +17,11 @@ "use strict";

let config = {
testIdAttribute: 'data-testid'
testIdAttribute: 'data-testid',
// this is to support React's async `act` function.
// forcing react-testing-library to wrap all async functions would've been
// a total nightmare (consider wrapping every findBy* query and then also
// updating `within` so those would be wrapped too. Total nightmare).
// so we have this config option that's really only intended for
// react-testing-library to use. For that reason, this feature will remain
// undocumented.
asyncWrapper: cb => cb()
};

@@ -20,0 +28,0 @@

@@ -227,2 +227,32 @@ 'use strict';

// It would be cleaner for this to live inside './queries', but
// other parts of the code assume that all exports from
// './queries' are query functions.
var config = {
testIdAttribute: 'data-testid',
// this is to support React's async `act` function.
// forcing react-testing-library to wrap all async functions would've been
// a total nightmare (consider wrapping every findBy* query and then also
// updating `within` so those would be wrapped too. Total nightmare).
// so we have this config option that's really only intended for
// react-testing-library to use. For that reason, this feature will remain
// undocumented.
asyncWrapper: function asyncWrapper(cb) {
return cb();
}
};
function configure(newConfig) {
if (typeof newConfig === 'function') {
// Pass the existing config out to the provided function
// and accept a delta in return
newConfig = newConfig(config);
} // Merge the incoming config delta
config = _extends({}, config, newConfig);
}
function getConfig() {
return config;
}
function waitForElement(callback, _temp) {

@@ -289,21 +319,11 @@ var _ref = _temp === void 0 ? {} : _temp,

// It would be cleaner for this to live inside './queries', but
// other parts of the code assume that all exports from
// './queries' are query functions.
var config = {
testIdAttribute: 'data-testid'
};
function configure(newConfig) {
if (typeof newConfig === 'function') {
// Pass the existing config out to the provided function
// and accept a delta in return
newConfig = newConfig(config);
} // Merge the incoming config delta
function waitForElementWrapper() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
config = _extends({}, config, newConfig);
return getConfig().asyncWrapper(function () {
return waitForElement.apply(void 0, args);
});
}
function getConfig() {
return config;
}

@@ -828,3 +848,3 @@ // The queries here should only be things that are accessible to both users who are using a screen reader

return function (container, text, options, waitForElementOptions) {
return waitForElement(function () {
return waitForElementWrapper(function () {
return getter(container, text, options);

@@ -948,2 +968,12 @@ }, waitForElementOptions);

function waitWrapper() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return getConfig().asyncWrapper(function () {
return wait.apply(void 0, args);
});
}
function waitForElementToBeRemoved(callback, _temp) {

@@ -1014,2 +1044,12 @@ var _ref = _temp === void 0 ? {} : _temp,

function waitForElementToBeRemovedWrapper() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return getConfig().asyncWrapper(function () {
return waitForElementToBeRemoved.apply(void 0, args);
});
}
function waitForDomChange(_temp) {

@@ -1054,2 +1094,12 @@ var _ref = _temp === void 0 ? {} : _temp,

function waitForDomChangeWrapper() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return getConfig().asyncWrapper(function () {
return waitForDomChange.apply(void 0, args);
});
}
var eventMap = {

@@ -1719,6 +1769,6 @@ // Clipboard Events

exports.queryHelpers = queryHelpers;
exports.wait = wait;
exports.waitForDomChange = waitForDomChange;
exports.waitForElement = waitForElement;
exports.waitForElementToBeRemoved = waitForElementToBeRemoved;
exports.wait = waitWrapper;
exports.waitForDomChange = waitForDomChangeWrapper;
exports.waitForElement = waitForElementWrapper;
exports.waitForElementToBeRemoved = waitForElementToBeRemovedWrapper;
exports.within = getQueriesForElement;

@@ -221,2 +221,32 @@ import _extends from '@babel/runtime/helpers/esm/extends';

// It would be cleaner for this to live inside './queries', but
// other parts of the code assume that all exports from
// './queries' are query functions.
var config = {
testIdAttribute: 'data-testid',
// this is to support React's async `act` function.
// forcing react-testing-library to wrap all async functions would've been
// a total nightmare (consider wrapping every findBy* query and then also
// updating `within` so those would be wrapped too. Total nightmare).
// so we have this config option that's really only intended for
// react-testing-library to use. For that reason, this feature will remain
// undocumented.
asyncWrapper: function asyncWrapper(cb) {
return cb();
}
};
function configure(newConfig) {
if (typeof newConfig === 'function') {
// Pass the existing config out to the provided function
// and accept a delta in return
newConfig = newConfig(config);
} // Merge the incoming config delta
config = _extends({}, config, newConfig);
}
function getConfig() {
return config;
}
function waitForElement(callback, _temp) {

@@ -283,21 +313,11 @@ var _ref = _temp === void 0 ? {} : _temp,

// It would be cleaner for this to live inside './queries', but
// other parts of the code assume that all exports from
// './queries' are query functions.
var config = {
testIdAttribute: 'data-testid'
};
function configure(newConfig) {
if (typeof newConfig === 'function') {
// Pass the existing config out to the provided function
// and accept a delta in return
newConfig = newConfig(config);
} // Merge the incoming config delta
function waitForElementWrapper() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
config = _extends({}, config, newConfig);
return getConfig().asyncWrapper(function () {
return waitForElement.apply(void 0, args);
});
}
function getConfig() {
return config;
}

@@ -822,3 +842,3 @@ // The queries here should only be things that are accessible to both users who are using a screen reader

return function (container, text, options, waitForElementOptions) {
return waitForElement(function () {
return waitForElementWrapper(function () {
return getter(container, text, options);

@@ -942,2 +962,12 @@ }, waitForElementOptions);

function waitWrapper() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return getConfig().asyncWrapper(function () {
return wait.apply(void 0, args);
});
}
function waitForElementToBeRemoved(callback, _temp) {

@@ -1008,2 +1038,12 @@ var _ref = _temp === void 0 ? {} : _temp,

function waitForElementToBeRemovedWrapper() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return getConfig().asyncWrapper(function () {
return waitForElementToBeRemoved.apply(void 0, args);
});
}
function waitForDomChange(_temp) {

@@ -1048,2 +1088,12 @@ var _ref = _temp === void 0 ? {} : _temp,

function waitForDomChangeWrapper() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return getConfig().asyncWrapper(function () {
return waitForDomChange.apply(void 0, args);
});
}
var eventMap = {

@@ -1643,2 +1693,2 @@ // Clipboard Events

export { getQueriesForElement as bindElementToQueries, configure, debugDOM, findAllByAltText, findAllByDisplayValue, findAllByLabelText, findAllByPlaceholderText, findAllByRole, findAllByTestId, findAllByText, findAllByTitle, findByAltText, findByDisplayValue, findByLabelText, findByPlaceholderText, findByRole, findByTestId, findByText, findByTitle, fireEvent, firstResultOrNull, getAllByAltText, getAllByDisplayValue, getAllByLabelText, getAllByPlaceholderText, getAllByRole, getAllBySelectText, getAllByTestId, getAllByText, getAllByTitle, getAllByValue, getByAltText, getByDisplayValue, getByLabelText, getByPlaceholderText, getByRole, getBySelectText, getByTestId, getByText, getByTitle, getByValue, getDefaultNormalizer, getElementError, getNodeText, getQueriesForElement, prettyDOM, defaultQueries as queries, queryAllByAltText, queryAllByAttribute, queryAllByDisplayValue, queryAllByLabelText, queryAllByPlaceholderText, queryAllByRole, queryAllBySelectText, queryAllByTestId, queryAllByText, queryAllByTitle, queryAllByValue, queryByAltText, queryByAttribute, queryByDisplayValue, queryByLabelText, queryByPlaceholderText, queryByRole, queryBySelectText, queryByTestId, queryByText, queryByTitle, queryByValue, queryHelpers, wait, waitForDomChange, waitForElement, waitForElementToBeRemoved, getQueriesForElement as within };
export { getQueriesForElement as bindElementToQueries, configure, debugDOM, findAllByAltText, findAllByDisplayValue, findAllByLabelText, findAllByPlaceholderText, findAllByRole, findAllByTestId, findAllByText, findAllByTitle, findByAltText, findByDisplayValue, findByLabelText, findByPlaceholderText, findByRole, findByTestId, findByText, findByTitle, fireEvent, firstResultOrNull, getAllByAltText, getAllByDisplayValue, getAllByLabelText, getAllByPlaceholderText, getAllByRole, getAllBySelectText, getAllByTestId, getAllByText, getAllByTitle, getAllByValue, getByAltText, getByDisplayValue, getByLabelText, getByPlaceholderText, getByRole, getBySelectText, getByTestId, getByText, getByTitle, getByValue, getDefaultNormalizer, getElementError, getNodeText, getQueriesForElement, prettyDOM, defaultQueries as queries, queryAllByAltText, queryAllByAttribute, queryAllByDisplayValue, queryAllByLabelText, queryAllByPlaceholderText, queryAllByRole, queryAllBySelectText, queryAllByTestId, queryAllByText, queryAllByTitle, queryAllByValue, queryByAltText, queryByAttribute, queryByDisplayValue, queryByLabelText, queryByPlaceholderText, queryByRole, queryBySelectText, queryByTestId, queryByText, queryByTitle, queryByValue, queryHelpers, waitWrapper as wait, waitForDomChangeWrapper as waitForDomChange, waitForElementWrapper as waitForElement, waitForElementToBeRemovedWrapper as waitForElementToBeRemoved, getQueriesForElement as within };

@@ -7,18 +7,108 @@ (function (global, factory) {

Object.keys(getQueriesForElement_js).forEach(function (key) { exports[key] = getQueriesForElement_js[key]; });
Object.keys(queries_js).forEach(function (key) { exports[key] = queries_js[key]; });
Object.keys(queryHelpers_js).forEach(function (key) { exports[key] = queryHelpers_js[key]; });
Object.keys(wait_js).forEach(function (key) { exports[key] = wait_js[key]; });
Object.keys(waitForElement_js).forEach(function (key) { exports[key] = waitForElement_js[key]; });
Object.keys(waitForElementToBeRemoved_js).forEach(function (key) { exports[key] = waitForElementToBeRemoved_js[key]; });
Object.keys(waitForDomChange_js).forEach(function (key) { exports[key] = waitForDomChange_js[key]; });
Object.keys(getNodeText_js).forEach(function (key) { exports[key] = getNodeText_js[key]; });
Object.keys(events_js).forEach(function (key) { exports[key] = events_js[key]; });
Object.keys(prettyDom_js).forEach(function (key) { exports[key] = prettyDom_js[key]; });
exports.bindElementToQueries = getQueriesForElement_js.getQueriesForElement;
exports.within = getQueriesForElement_js.getQueriesForElement;
Object.keys(getQueriesForElement_js).forEach(function (key) {
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return getQueriesForElement_js[key];
}
});
});
Object.keys(queries_js).forEach(function (key) {
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return queries_js[key];
}
});
});
Object.keys(queryHelpers_js).forEach(function (key) {
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return queryHelpers_js[key];
}
});
});
Object.keys(wait_js).forEach(function (key) {
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return wait_js[key];
}
});
});
Object.keys(waitForElement_js).forEach(function (key) {
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return waitForElement_js[key];
}
});
});
Object.keys(waitForElementToBeRemoved_js).forEach(function (key) {
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return waitForElementToBeRemoved_js[key];
}
});
});
Object.keys(waitForDomChange_js).forEach(function (key) {
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return waitForDomChange_js[key];
}
});
});
Object.keys(getNodeText_js).forEach(function (key) {
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return getNodeText_js[key];
}
});
});
Object.keys(events_js).forEach(function (key) {
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return events_js[key];
}
});
});
Object.keys(prettyDom_js).forEach(function (key) {
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return prettyDom_js[key];
}
});
});
Object.defineProperty(exports, 'bindElementToQueries', {
enumerable: true,
get: function () {
return getQueriesForElement_js.getQueriesForElement;
}
});
Object.defineProperty(exports, 'within', {
enumerable: true,
get: function () {
return getQueriesForElement_js.getQueriesForElement;
}
});
exports.queries = queries_js;
exports.queryHelpers = queryHelpers_js;
exports.getDefaultNormalizer = matches_js.getDefaultNormalizer;
exports.configure = config_js.configure;
Object.defineProperty(exports, 'getDefaultNormalizer', {
enumerable: true,
get: function () {
return matches_js.getDefaultNormalizer;
}
});
Object.defineProperty(exports, 'configure', {
enumerable: true,
get: function () {
return config_js.configure;
}
});

@@ -25,0 +115,0 @@ Object.defineProperty(exports, '__esModule', { value: true });

@@ -1,2 +0,2 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("./get-queries-for-element.js"),require("./queries.js"),require("./query-helpers.js"),require("./wait.js"),require("./wait-for-element.js"),require("./wait-for-element-to-be-removed.js"),require("./wait-for-dom-change.js"),require("./matches.js"),require("./get-node-text.js"),require("./events.js"),require("./pretty-dom.js"),require("./config.js")):"function"==typeof define&&define.amd?define(["exports","./get-queries-for-element.js","./queries.js","./query-helpers.js","./wait.js","./wait-for-element.js","./wait-for-element-to-be-removed.js","./wait-for-dom-change.js","./matches.js","./get-node-text.js","./events.js","./pretty-dom.js","./config.js"],t):t((e=e||self).DomTestingLibrary={},e.getQueriesForElement_js,e.queries_js,e.queryHelpers_js,e.wait_js,e.waitForElement_js,e.waitForElementToBeRemoved_js,e.waitForDomChange_js,e.matches_js,e.getNodeText_js,e.events_js,e.prettyDom_js,e.config_js)}(this,function(e,t,r,s,o,i,n,j,u,f,c,a,m){"use strict";Object.keys(t).forEach(function(r){e[r]=t[r]}),Object.keys(r).forEach(function(t){e[t]=r[t]}),Object.keys(s).forEach(function(t){e[t]=s[t]}),Object.keys(o).forEach(function(t){e[t]=o[t]}),Object.keys(i).forEach(function(t){e[t]=i[t]}),Object.keys(n).forEach(function(t){e[t]=n[t]}),Object.keys(j).forEach(function(t){e[t]=j[t]}),Object.keys(f).forEach(function(t){e[t]=f[t]}),Object.keys(c).forEach(function(t){e[t]=c[t]}),Object.keys(a).forEach(function(t){e[t]=a[t]}),e.bindElementToQueries=t.getQueriesForElement,e.within=t.getQueriesForElement,e.queries=r,e.queryHelpers=s,e.getDefaultNormalizer=u.getDefaultNormalizer,e.configure=m.configure,Object.defineProperty(e,"__esModule",{value:!0})});
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("./get-queries-for-element.js"),require("./queries.js"),require("./query-helpers.js"),require("./wait.js"),require("./wait-for-element.js"),require("./wait-for-element-to-be-removed.js"),require("./wait-for-dom-change.js"),require("./matches.js"),require("./get-node-text.js"),require("./events.js"),require("./pretty-dom.js"),require("./config.js")):"function"==typeof define&&define.amd?define(["exports","./get-queries-for-element.js","./queries.js","./query-helpers.js","./wait.js","./wait-for-element.js","./wait-for-element-to-be-removed.js","./wait-for-dom-change.js","./matches.js","./get-node-text.js","./events.js","./pretty-dom.js","./config.js"],t):t((e=e||self).DomTestingLibrary={},e.getQueriesForElement_js,e.queries_js,e.queryHelpers_js,e.wait_js,e.waitForElement_js,e.waitForElementToBeRemoved_js,e.waitForDomChange_js,e.matches_js,e.getNodeText_js,e.events_js,e.prettyDom_js,e.config_js)}(this,function(e,t,r,n,o,i,u,f,s,c,j,a,b){"use strict";Object.keys(t).forEach(function(r){Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[r]}})}),Object.keys(r).forEach(function(t){Object.defineProperty(e,t,{enumerable:!0,get:function(){return r[t]}})}),Object.keys(n).forEach(function(t){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n[t]}})}),Object.keys(o).forEach(function(t){Object.defineProperty(e,t,{enumerable:!0,get:function(){return o[t]}})}),Object.keys(i).forEach(function(t){Object.defineProperty(e,t,{enumerable:!0,get:function(){return i[t]}})}),Object.keys(u).forEach(function(t){Object.defineProperty(e,t,{enumerable:!0,get:function(){return u[t]}})}),Object.keys(f).forEach(function(t){Object.defineProperty(e,t,{enumerable:!0,get:function(){return f[t]}})}),Object.keys(c).forEach(function(t){Object.defineProperty(e,t,{enumerable:!0,get:function(){return c[t]}})}),Object.keys(j).forEach(function(t){Object.defineProperty(e,t,{enumerable:!0,get:function(){return j[t]}})}),Object.keys(a).forEach(function(t){Object.defineProperty(e,t,{enumerable:!0,get:function(){return a[t]}})}),Object.defineProperty(e,"bindElementToQueries",{enumerable:!0,get:function(){return t.getQueriesForElement}}),Object.defineProperty(e,"within",{enumerable:!0,get:function(){return t.getQueriesForElement}}),e.queries=r,e.queryHelpers=n,Object.defineProperty(e,"getDefaultNormalizer",{enumerable:!0,get:function(){return s.getDefaultNormalizer}}),Object.defineProperty(e,"configure",{enumerable:!0,get:function(){return b.configure}}),Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=dom-testing-library.umd.min.js.map

@@ -6,6 +6,8 @@ "use strict";

});
exports.waitForDomChange = waitForDomChange;
exports.waitForDomChange = waitForDomChangeWrapper;
var _helpers = require("./helpers");
var _config = require("./config");
function waitForDomChange({

@@ -42,2 +44,6 @@ container = (0, _helpers.getDocument)(),

});
}
function waitForDomChangeWrapper(...args) {
return (0, _config.getConfig)().asyncWrapper(() => waitForDomChange(...args));
}

@@ -6,6 +6,8 @@ "use strict";

});
exports.waitForElementToBeRemoved = waitForElementToBeRemoved;
exports.waitForElementToBeRemoved = waitForElementToBeRemovedWrapper;
var _helpers = require("./helpers");
var _config = require("./config");
function waitForElementToBeRemoved(callback, {

@@ -68,2 +70,6 @@ container = (0, _helpers.getDocument)(),

});
}
function waitForElementToBeRemovedWrapper(...args) {
return (0, _config.getConfig)().asyncWrapper(() => waitForElementToBeRemoved(...args));
}

@@ -6,6 +6,8 @@ "use strict";

});
exports.waitForElement = waitForElement;
exports.waitForElement = waitForElementWrapper;
var _helpers = require("./helpers");
var _config = require("./config");
function waitForElement(callback, {

@@ -64,2 +66,6 @@ container = (0, _helpers.getDocument)(),

});
}
function waitForElementWrapper(...args) {
return (0, _config.getConfig)().asyncWrapper(() => waitForElement(...args));
}

@@ -8,6 +8,8 @@ "use strict";

});
exports.wait = wait;
exports.wait = waitWrapper;
var _waitForExpect = _interopRequireDefault(require("wait-for-expect"));
var _config = require("./config");
function wait(callback = () => {}, {

@@ -18,2 +20,6 @@ timeout = 4500,

return (0, _waitForExpect.default)(callback, timeout, interval);
}
function waitWrapper(...args) {
return (0, _config.getConfig)().asyncWrapper(() => wait(...args));
}
{
"name": "dom-testing-library",
"version": "3.18.2",
"version": "3.19.0",
"description": "Simple and complete DOM testing utilities that encourage good testing practices.",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

export interface IConfig {
testIdAttribute: string
asyncWrapper<T>(cb: Function): Promise<T>
}

@@ -4,0 +5,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc