text stringlengths 3 1.39M | id stringlengths 16 173 | metadata dict | __index_level_0__ int64 0 363 |
|---|---|---|---|
{
"recommendations": ["esbenp.prettier-vscode"]
}
| cypress-commands/.vscode/extentions.json/0 | {
"file_path": "cypress-commands/.vscode/extentions.json",
"repo_id": "cypress-commands",
"token_count": 26
} | 0 |
import whitespace from '../../../src/utils/whitespace';
const _ = Cypress._;
describe('Whitespace options for commands yielding strings', function () {
it('returns a function', function () {
expect(_.isFunction(whitespace('mode'))).to.be.true;
});
context('mode = `simplify`', function () {
beforeEach(function () {
this.ws = whitespace('simplify');
});
it('simplifies whitespace in the middle of the string', function () {
expect(this.ws('Lorum ipsum\n\xa0dolor\tsit \r \n\tamet')).to.equal(
'Lorum ipsum dolor sit amet'
);
});
it('removes whitespace at the ends of the string', function () {
expect(this.ws(' Lorum ipsum dolor sit amet\n')).to.equal('Lorum ipsum dolor sit amet');
expect(this.ws('\tLorum ipsum dolor sit amet\r')).to.equal(
'Lorum ipsum dolor sit amet'
);
expect(this.ws('\t \r \n\xa0 Lorum ipsum dolor sit amet')).to.equal(
'Lorum ipsum dolor sit amet'
);
});
it('removes zero-width whitespace', function () {
expect(this.ws('Lorum\u200Bipsum dol\uFEFFor sit amet')).to.equal(
'Lorumipsum dolor sit amet'
);
expect(this.ws('Lorum\u200Cips\uFEFFum dolor sit amet')).to.equal(
'Lorumipsum dolor sit amet'
);
expect(this.ws('Lorum\u200Dipsum dolor sit am\uFEFFet')).to.equal(
'Lorumipsum dolor sit amet'
);
});
});
context('mode = `keep-newline`', function () {
beforeEach(function () {
this.ws = whitespace('keep-newline');
});
it('simplifies non-newline whitespace in the middle of the string', function () {
expect(this.ws('Lorum ipsum dolor\tsit \r \tamet')).to.equal(
'Lorum ipsum dolor sit amet'
);
});
it('keeps newline characters in the middle of a string', function () {
expect(this.ws('Lorum \n ipsum\xa0 dolor\tsit \r \n\tamet')).to.equal(
'Lorum\nipsum dolor sit\namet'
);
});
it('removes non-newline whitespace at the ends of the string', function () {
expect(this.ws(' Lorum ipsum dolor sit amet')).to.equal('Lorum ipsum dolor sit amet');
expect(this.ws('\tLorum ipsum dolor sit amet\r')).to.equal(
'Lorum ipsum dolor sit amet'
);
expect(this.ws('\t\xa0 \r Lorum ipsum dolor sit amet')).to.equal(
'Lorum ipsum dolor sit amet'
);
});
it('keeps newline characters at the ends of a string', function () {
expect(this.ws(' \n Lorum ipsum dolor sit amet\t\n')).to.equal(
'\nLorum ipsum dolor sit amet\n'
);
expect(this.ws('\nLorum ipsum dolor sit amet')).to.equal(
'\nLorum ipsum dolor sit amet'
);
});
it('removes zero-width whitespace', function () {
expect(this.ws('Lorum\u200Bipsum dol\uFEFFor sit amet')).to.equal(
'Lorumipsum dolor sit amet'
);
expect(this.ws('Lorum\u200Cips\uFEFFum dolor sit amet')).to.equal(
'Lorumipsum dolor sit amet'
);
expect(this.ws('Lorum\u200Dipsum dolor sit am\uFEFFet')).to.equal(
'Lorumipsum dolor sit amet'
);
});
});
context('mode = `keep`', function () {
beforeEach(function () {
this.ws = whitespace('keep');
});
it('does not change the string at all', function () {
const string = 'Lorum \t\r\xa0 ipsum dolor \n\nsit amet\n\r';
expect(this.ws(string)).to.equal(string);
});
});
});
| cypress-commands/cypress/e2e/utils/whitespace.cy.js/0 | {
"file_path": "cypress-commands/cypress/e2e/utils/whitespace.cy.js",
"repo_id": "cypress-commands",
"token_count": 1999
} | 1 |
const _ = Cypress._;
const $ = Cypress.$;
import isJquery from './utils/isJquery';
import OptionValidator from './utils/optionValidator';
const validator = new OptionValidator('then');
/**
* Enables you to work with the subject yielded from the previous command.
*
* @example
* cy.then((subject) => {
* // ...
* });
*
* @param {function} fn
* @param {Object} options
* @param {boolean} [options.log=false]
* Log to Cypress bar
* @param {boolean} [options.retry=false]
* Retry when an upcomming assertion fails
*
* @yields {any}
* @since 0.0.0
*/
Cypress.Commands.overwrite('then', (originalCommand, subject, fn, options = {}) => {
if (_.isFunction(options)) {
// Flip the values of `fn` and `options`
[fn, options] = [options, fn];
}
validator.check('log', options.log, [true, false]);
validator.check('retry', options.retry, [true, false]);
if (options.retry && typeof options.log === 'undefined') {
options.log = true;
}
_.defaults(options, {
log: false,
retry: false,
});
// Setup logging
const consoleProps = {};
if (options.log) {
options._log = Cypress.log({
name: 'then',
message: '',
consoleProps: () => consoleProps,
});
if (isJquery(subject)) {
// Link the DOM element to the logger
options._log.set('$el', $(subject));
consoleProps['Applied to'] = $(subject);
} else {
consoleProps['Applied to'] = String(subject);
}
if (options.retry) {
options._log.set('message', 'retry');
}
}
/**
* This function is recursively called untill timeout or the upcomming
* assertion passes. Keep this function as fast as possible.
*
* @return {Promise}
*/
async function executeFnAndRetry() {
const result = await executeFn();
return cy.verifyUpcomingAssertions(result, options, {
// Try again by calling itself
onRetry: executeFnAndRetry,
});
}
/**
* Execute the provided callback function
*
* @return {*}
*/
async function executeFn() {
// Execute using the original `then` to not reinvent the wheel
return await originalCommand(subject, options, fn).then((value) => {
if (options.log) {
consoleProps.Yielded = value;
}
return value;
});
}
if (options.retry) {
return executeFnAndRetry();
}
return executeFn();
});
| cypress-commands/src/then.js/0 | {
"file_path": "cypress-commands/src/then.js",
"repo_id": "cypress-commands",
"token_count": 1101
} | 2 |
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
| cypress-drag-drop/LICENSE/0 | {
"file_path": "cypress-drag-drop/LICENSE",
"repo_id": "cypress-drag-drop",
"token_count": 8075
} | 3 |
describe('Drag drop', () => {
it('should be able to drag and drop elements', () => {
cy.visit('/')
cy.setExample('Basic')
cy.findByTestId('left').find('.item').assertList(['1', '2', '3', '4', '5', '6'])
cy.findByTestId('item-1')
.drag('[data-testid="right"]', { target: { position: 'left' } })
.then((success) => {
assert.isTrue(success)
})
cy.findByTestId('right').find('.item').assertList(['1'])
cy.findByTestId('left').find('.item').assertList(['2', '3', '4', '5', '6'])
})
})
| cypress-drag-drop/tests/specs/basic.cy.js/0 | {
"file_path": "cypress-drag-drop/tests/specs/basic.cy.js",
"repo_id": "cypress-drag-drop",
"token_count": 235
} | 4 |
# Contributing
## Questions
If you have questions about implementation details, help or support, then please use our dedicated community forum at [Github Discussions](https://github.com/msmps/cypress-layout-inspector/discussions) **PLEASE NOTE:** If you choose to instead open an issue for your question, your issue will be immediately closed and redirected to the forum.
## Reporting Issues
If you have found what you think is a bug, please [file an issue](https://github.com/msmps/cypress-layout-inspector/issues/new). **PLEASE NOTE:** Issues that are identified as implementation questions or non-issues will be immediately closed and redirected to [Github Discussions](https://github.com/msmps/cypress-layout-inspector/discussions)
## Suggesting new features
If you are here to suggest a feature, first create an issue if it does not already exist. From there, we will discuss use-cases for the feature and then finally discuss how it could be implemented.
## Development
If you have been assigned to fix an issue or develop a new feature, please follow these steps to get started:
- Fork this repository
- Install dependencies by running `$ npm install`
- Link `cypress-layout-inspector` locally by running `$ npm link`
- Auto-build files as you edit by running `$ npm run build`
- Implement your changes to files in the `src/` directory and corresponding test files in `cypress/`
- To run examples, follow their individual directions. Usually this is just `$ npm run test:debug`
- To run examples using your local build, link to the local `cypress-layout-inspector` by running `$ npm link cypress-layout-inspector` from the example's directory
- Document your changes in the appropriate doc page
- Git stage your required chnages and commit (see below commit guidelines)
- Submit PR for review
## Commit message conventions
`cypress-layout-inspector` is using [Angular Commit Message Conventions](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines).
We have very precise rules over how our git commit messages can be formatted. This leads to **more readable messages** that are easy to follow when looking through the **project history**.
### Commit Message Format
**Consider using: npx git-cz**
Each commit message consists of a **header**, a **body** and a **footer**. The header has a special
format that includes a **type**, a **scope** and a **subject**:
```
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
```
The **header** is mandatory and the **scope** of the header is optional.
Any line of the commit message cannot be longer than 100 characters! This allows the message to be easier to read on GitHub as well as in various git tools.
### Type
Must be one of the following:
- **feat**: A new feature
- **fix**: A bug fix
- **docs**: Documentation only changes
- **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing
semi-colons, etc)
- **refactor**: A code change that neither fixes a bug nor adds a feature
- **perf**: A code change that improves performance
- **test**: Adding missing or correcting existing tests
- **chore**: Changes to the build process or auxiliary tools and libraries such as documentation
generation
### Scope
The scope could be anything specifying place of the commit change. For example `alignment`, `position` etc...
You can use `*` when the change affects more than a single scope.
### Subject
The subject contains succinct description of the change:
- use the imperative, present tense: "change" not "changed" nor "changes"
- don't capitalize first letter
- no dot (.) at the end
### Body
Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes". The body should include the motivation for the change and contrast this with previous behavior.
### Footer
The footer should contain any information about **Breaking Changes** and is also the place to [reference GitHub issues that this commit closes](https://help.github.com/en/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue).
**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.
### Example
Here is an example of the release type that will be done based on a commit messages:
| Commit message | Release type |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------- |
| `fix(pencil): stop graphite breaking when too much pressure applied` | Patch Release |
| `feat(pencil): add 'graphiteWidth' option` | ~~Minor~~ Feature Release |
| `perf(pencil): remove graphiteWidth option`<br><br>`BREAKING CHANGE: The graphiteWidth option has been removed.`<br>`The default graphite width of 10mm is always used for performance reasons.` | ~~Major~~ Breaking Release |
### Revert
If the commit reverts a previous commit, it should begin with `revert:`, followed by the header of the reverted commit. In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted.
## Pull requests
Maintainers merge pull requests by squashing all commits and editing the commit message if necessary using the GitHub user interface.
Use an appropriate commit type. Be especially careful with breaking changes.
## Releases
For each new commit added to `master` with `git push` or by merging a pull request or merging from another branch, a github action is triggered and runs the `semantic-release` command to make a release if there are codebase changes since the last release that affect the package functionalities.
| cypress-layout-inspector/CONTRIBUTING.md/0 | {
"file_path": "cypress-layout-inspector/CONTRIBUTING.md",
"repo_id": "cypress-layout-inspector",
"token_count": 1955
} | 5 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>cypress-layout-inspector test application</title>
<style>
*,
*::before,
*::after {
box-sizing: border-box;
}
.container {
display: flex;
flex-direction: column;
padding: 15px;
border: 1px solid lightgray;
max-width: 230px;
}
.block {
display: inline-flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
border: 1px dotted blue;
}
.block + .block {
margin-top: 50px;
border-color: red;
}
.block-2 {
width: 100px;
}
.block-4 {
width: 100px;
margin-left: 100px;
}
.block-8 {
width: 100px;
margin-left: 50px;
}
</style>
</head>
<body>
<pre>block-2 vertically aligned left of block-1</pre>
<div class="container">
<div class="block block-1">1</div>
<div class="block block-2">2</div>
</div>
<!-- -->
<pre>block-4 vertically aligned right of block-3</pre>
<div class="container">
<div class="block block-3">3</div>
<div class="block block-4">4</div>
</div>
<!-- -->
<pre>block-6 vertically aligned all with block-5</pre>
<div class="container">
<div class="block block-5">5</div>
<div class="block block-6">6</div>
</div>
<!-- -->
<pre>block-8 vertically aligned centered with block-7</pre>
<div class="container">
<div class="block block-7">7</div>
<div class="block block-8">8</div>
</div>
<!-- -->
</body>
</html>
| cypress-layout-inspector/cypress/fixtures/vertical.html/0 | {
"file_path": "cypress-layout-inspector/cypress/fixtures/vertical.html",
"repo_id": "cypress-layout-inspector",
"token_count": 877
} | 6 |
import dimensionsOverwrites from "./dimensions";
chai.use(dimensionsOverwrites);
| cypress-layout-inspector/src/overwrites/index.ts/0 | {
"file_path": "cypress-layout-inspector/src/overwrites/index.ts",
"repo_id": "cypress-layout-inspector",
"token_count": 25
} | 7 |
module.exports = {
plugins: [
"@semantic-release/release-notes-generator",
"@semantic-release/github",
"@semantic-release/npm"
]
};
| cypress-wait-until/release.config.js/0 | {
"file_path": "cypress-wait-until/release.config.js",
"repo_id": "cypress-wait-until",
"token_count": 59
} | 8 |
{
"eslint.alwaysShowStatus": true,
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"json"
],
"eslint.enable": true,
// this project does not use Prettier
// thus set all settings to disable accidentally running Prettier
"prettier.requireConfig": true,
"prettier.disableLanguages": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"json"
],
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"typescript.tsdk": "node_modules/typescript/lib",
// Support autocompletion and preview of strings.
// Additionally, support extraction of hardcoded strings into key-values.
"i18n-ally.localesPaths": "packages/frontend-shared/src/locales",
"i18n-ally.displayLanguage": "en-US",
"i18n-ally.enabledFrameworks": ["vue"],
"i18n-ally.extract.keyPrefix": "{fileNameWithoutExt}.",
"i18n-ally.extract.keyMaxLength": 40,
"i18n-ally.keystyle": "nested",
// Volar is the main extension that powers Vue's language features.
// These are commented out because they slow down node development
// "volar.autoCompleteRefs": false,
"volar.takeOverMode.enabled": "auto",
"editor.tabSize": 2,
}
| cypress/.vscode/settings.json/0 | {
"file_path": "cypress/.vscode/settings.json",
"repo_id": "cypress",
"token_count": 444
} | 9 |
exports['getJustVersion returns semver if passed 1'] = `
0.20.1
`
exports['getJustVersion returns semver with tag if passed 1'] = `
1.0.0-dev
`
exports['getJustVersion returns name if starts with cypress 1'] = `
cypress@dev
`
exports['getJustVersion returns name if starts with cypress 2'] = `
cypress@alpha
`
exports['getJustVersion returns name if starts with cypress 3'] = `
cypress@0.20.3
`
exports['getJustVersion returns name if matches cypress 1'] = `
cypress
`
exports['getJustVersion extracts version from url 1'] = {
"url": "https://foo.com/npm/0.20.3/develop-sha-13992/cypress.tgz",
"version": "0.20.3"
}
exports['getJustVersion extracts version with dev from url 1'] = {
"url": "https://foo.com/npm/0.20.3-dev/develop-sha-13992/cypress.tgz",
"version": "0.20.3-dev"
}
exports['getJustVersion for anything else returns the input 1'] = {
"url": "babababa",
"version": "babababa"
}
| cypress/__snapshots__/utils-spec.js/0 | {
"file_path": "cypress/__snapshots__/utils-spec.js",
"repo_id": "cypress",
"token_count": 334
} | 10 |
# CLI
The CLI is used to build the [cypress npm module](https://www.npmjs.com/package/cypress) to be run within a terminal.
**The CLI has the following responsibilities:**
- Allow users to print CLI commands
- Allow users to install the Cypress executable
- Allow users to print their current Cypress version
- Allow users to run Cypress tests from the terminal
- Allow users to open Cypress in the interactive Test Runner.
- Allow users to verify that Cypress is installed correctly and executable
- Allow users to manages the Cypress binary cache
- Allow users to pass in options that change way tests are ran or recorded (browsers used, specfiles ran, grouping, parallelization)
## Building
See `scripts/build.js`. Note that the built npm package will include [NPM_README.md](NPM_README.md) as its public README file.
## Testing
### Automated
From the repo's root, you can run unit tests with:
```bash
yarn test-unit --scope cypress
yarn test-watch --scope cypress
yarn test-debug --scope cypress
```
### Updating snapshots
Prepend `SNAPSHOT_UPDATE=1` to any test command. See [`snap-shot-it` instructions](https://github.com/bahmutov/snap-shot-it#advanced-use) for more info.
```bash
SNAPSHOT_UPDATE=1 yarn test-unit --scope cypress
```
#### Type Linting
When testing with `dtslint`, you may need to remove existing typescript installations before running the type linter (for instance, on OS X, you might `rm -rf ~/.dts/typescript-installs`) in order to reproduce issues with new versions of typescript (i.e., `@next`).
### Manual
To build and test an NPM package:
- `yarn`
- `yarn build`
This creates `build` folder.
- `cd build; yarn pack`
This creates an archive, usually named `cypress-v<version>.tgz`. You can install this archive from other projects, but because there is no corresponding binary yet (probably), skip binary download. For example from inside `cypress-example-kitchensink` folder
```shell
yarn add ~/{your-dirs}/cypress/cli/build/cypress-3.3.1.tgz --ignore-scripts
```
Which installs the `tgz` file we have just built from folder `Users/jane-lane/{your-dirs}/cypress/cli/build`.
#### Sub-package API
> How do deep imports from cypress/* get resolved?
The cypress npm package comes pre-assembled with mounting libraries for major front-end frameworks. These mounting libraries are the first examples of Cypress providing re-exported sub-packages. These sub-packages follow the same naming convention they do when they're published on **npm**, but without a leading **`@`** sign. For example:
##### An example of a sub-package: @cypress/vue, @cypress/react, @cypress/mount-utils
**Let's discuss the Vue mounting library that Cypress ships.**
If you'd installed the `@cypress/vue` package from NPM, you could write the following code.
This would be necessary when trying to use a version of Vue, React, or other library that may be newer or older than the current version of cypress itself.
```js
import { mount } from '@cypress/vue'
```
Now, with the sub-package API, you're able to import the latest APIs directly from Cypress without needing to install a separate dependency.
```js
import { mount } from 'cypress/vue'
```
The only difference is the import name, and if you still need to use a specific version of one of our external sub-packages, you may install it and import it directly.
##### Adding a new sub-package
There are a few steps when adding a new sub-package.
1. Make sure the sub-package's rollup build is _self-contained_ or that any dependencies are also declared in the CLI's **`package.json`**.
2. Now, in the **`postbuild`** script for the sub-package you'd like to embed, invoke `node ./scripts/sync-exported-npm-with-cli.js` (relative to the sub-package, see **`npm/vue`** for an example).
3. Add the sub-package's name to the following locations:
- **`cli/.gitignore`**
- **`cli/scripts/post-build.js`**
- **`.eslintignore`** (under cli/sub-package)
4. DO NOT manually update the **package.json** file. Running `yarn build` will automate this process.
5. Commit the changed files.
[Here is an example Pull Request](https://github.com/cypress-io/cypress/pull/20930/files#diff-21b1fe66043572c76c549a4fc5f186e9a69c330b186fc91116b9b70a4d047902)
#### Module API
The module API can be tested locally using something like:
```typescript
/* @ts-ignore */
import cypress from '../../cli/lib/cypress'
const run = cypress.run as (options?: Partial<CypressCommandLine.CypressRunOptions>) => Promise<CypressCommandLine.CypressRunResult | CypressCommandLine.CypressFailedRunResult>
run({
spec: './cypress/component/advanced/framer-motion/Motion.spec.tsx',
testingType: 'component',
/* @ts-ignore */
dev: true,
}).then(results => {
console.log(results)
})
```
Note that the `dev` flag is required for local testing, as otherwise the command will fail with a binary error.
| cypress/cli/README.md/0 | {
"file_path": "cypress/cli/README.md",
"repo_id": "cypress",
"token_count": 1447
} | 11 |
const minimist = require('minimist')
const debug = require('debug')('cypress:cli')
const args = minimist(process.argv.slice(2))
const util = require('./lib/util')
// we're being used from the command line
switch (args.exec) {
case 'install':
debug('installing Cypress from NPM')
require('./lib/tasks/install')
.start({ force: args.force })
.catch(util.logErrorExit1)
break
case 'verify':
// for simple testing in the monorepo
debug('verifying Cypress')
require('./lib/tasks/verify')
.start({ force: true }) // always force verification
.catch(util.logErrorExit1)
break
default:
debug('exporting Cypress module interface')
module.exports = require('./lib/cypress')
}
| cypress/cli/index.js/0 | {
"file_path": "cypress/cli/index.js",
"repo_id": "cypress",
"token_count": 258
} | 12 |
const la = require('lazy-ass')
const is = require('check-more-types')
const os = require('os')
const url = require('url')
const path = require('path')
const debug = require('debug')('cypress:cli')
const request = require('@cypress/request')
const Promise = require('bluebird')
const requestProgress = require('request-progress')
const { stripIndent } = require('common-tags')
const getProxyForUrl = require('proxy-from-env').getProxyForUrl
const { throwFormErrorText, errors } = require('../errors')
const fs = require('../fs')
const util = require('../util')
const defaultBaseUrl = 'https://download.cypress.io/'
const defaultMaxRedirects = 10
const getProxyForUrlWithNpmConfig = (url) => {
return getProxyForUrl(url) ||
process.env.npm_config_https_proxy ||
process.env.npm_config_proxy ||
null
}
const getBaseUrl = () => {
if (util.getEnv('CYPRESS_DOWNLOAD_MIRROR')) {
let baseUrl = util.getEnv('CYPRESS_DOWNLOAD_MIRROR')
if (!baseUrl.endsWith('/')) {
baseUrl += '/'
}
return baseUrl
}
return defaultBaseUrl
}
const getCA = () => {
return new Promise((resolve) => {
if (process.env.npm_config_cafile) {
fs.readFile(process.env.npm_config_cafile, 'utf8')
.then((cafileContent) => {
resolve(cafileContent)
})
.catch(() => {
resolve()
})
} else if (process.env.npm_config_ca) {
resolve(process.env.npm_config_ca)
} else {
resolve()
}
})
}
const prepend = (arch, urlPath, version) => {
const endpoint = url.resolve(getBaseUrl(), urlPath)
const platform = os.platform()
const pathTemplate = util.getEnv('CYPRESS_DOWNLOAD_PATH_TEMPLATE', true)
return pathTemplate
? (
pathTemplate
.replace(/\\?\$\{endpoint\}/g, endpoint)
.replace(/\\?\$\{platform\}/g, platform)
.replace(/\\?\$\{arch\}/g, arch)
.replace(/\\?\$\{version\}/g, version)
)
: `${endpoint}?platform=${platform}&arch=${arch}`
}
const getUrl = (arch, version) => {
if (is.url(version)) {
debug('version is already an url', version)
return version
}
const urlPath = version ? `desktop/${version}` : 'desktop'
return prepend(arch, urlPath, version)
}
const statusMessage = (err) => {
return (err.statusCode
? [err.statusCode, err.statusMessage].join(' - ')
: err.toString())
}
const prettyDownloadErr = (err, url) => {
const msg = stripIndent`
URL: ${url}
${statusMessage(err)}
`
debug(msg)
return throwFormErrorText(errors.failedDownload)(msg)
}
/**
* Checks checksum and file size for the given file. Allows both
* values or just one of them to be checked.
*/
const verifyDownloadedFile = (filename, expectedSize, expectedChecksum) => {
if (expectedSize && expectedChecksum) {
debug('verifying checksum and file size')
return Promise.join(
util.getFileChecksum(filename),
util.getFileSize(filename),
(checksum, filesize) => {
if (checksum === expectedChecksum && filesize === expectedSize) {
debug('downloaded file has the expected checksum and size ✅')
return
}
debug('raising error: checksum or file size mismatch')
const text = stripIndent`
Corrupted download
Expected downloaded file to have checksum: ${expectedChecksum}
Computed checksum: ${checksum}
Expected downloaded file to have size: ${expectedSize}
Computed size: ${filesize}
`
debug(text)
throw new Error(text)
},
)
}
if (expectedChecksum) {
debug('only checking expected file checksum %d', expectedChecksum)
return util.getFileChecksum(filename)
.then((checksum) => {
if (checksum === expectedChecksum) {
debug('downloaded file has the expected checksum ✅')
return
}
debug('raising error: file checksum mismatch')
const text = stripIndent`
Corrupted download
Expected downloaded file to have checksum: ${expectedChecksum}
Computed checksum: ${checksum}
`
throw new Error(text)
})
}
if (expectedSize) {
// maybe we don't have a checksum, but at least CDN returns content length
// which we can check against the file size
debug('only checking expected file size %d', expectedSize)
return util.getFileSize(filename)
.then((filesize) => {
if (filesize === expectedSize) {
debug('downloaded file has the expected size ✅')
return
}
debug('raising error: file size mismatch')
const text = stripIndent`
Corrupted download
Expected downloaded file to have size: ${expectedSize}
Computed size: ${filesize}
`
throw new Error(text)
})
}
debug('downloaded file lacks checksum or size to verify')
return Promise.resolve()
}
// downloads from given url
// return an object with
// {filename: ..., downloaded: true}
const downloadFromUrl = ({ url, downloadDestination, progress, ca, version, redirectTTL = defaultMaxRedirects }) => {
if (redirectTTL <= 0) {
return Promise.reject(new Error(
stripIndent`
Failed downloading the Cypress binary.
There were too many redirects. The default allowance is ${defaultMaxRedirects}.
Maybe you got stuck in a redirect loop?
`,
))
}
return new Promise((resolve, reject) => {
const proxy = getProxyForUrlWithNpmConfig(url)
debug('Downloading package', {
url,
proxy,
downloadDestination,
})
if (ca) {
debug('using custom CA details from npm config')
}
const reqOptions = {
uri: url,
...(proxy ? { proxy } : {}),
...(ca ? { agentOptions: { ca } } : {}),
method: 'GET',
followRedirect: false,
}
const req = request(reqOptions)
// closure
let started = null
let expectedSize
let expectedChecksum
requestProgress(req, {
throttle: progress.throttle,
})
.on('response', (response) => {
// we have computed checksum and filesize during test runner binary build
// and have set it on the S3 object as user meta data, available via
// these custom headers "x-amz-meta-..."
// see https://github.com/cypress-io/cypress/pull/4092
expectedSize = response.headers['x-amz-meta-size'] ||
response.headers['content-length']
expectedChecksum = response.headers['x-amz-meta-checksum']
if (expectedChecksum) {
debug('expected checksum %s', expectedChecksum)
}
if (expectedSize) {
// convert from string (all Amazon custom headers are strings)
expectedSize = Number(expectedSize)
debug('expected file size %d', expectedSize)
}
// start counting now once we've gotten
// response headers
started = new Date()
if (/^3/.test(response.statusCode)) {
const redirectVersion = response.headers['x-version']
const redirectUrl = response.headers.location
debug('redirect version:', redirectVersion)
debug('redirect url:', redirectUrl)
downloadFromUrl({ url: redirectUrl, progress, ca, downloadDestination, version: redirectVersion, redirectTTL: redirectTTL - 1 })
.then(resolve).catch(reject)
// if our status code does not start with 200
} else if (!/^2/.test(response.statusCode)) {
debug('response code %d', response.statusCode)
const err = new Error(
stripIndent`
Failed downloading the Cypress binary.
Response code: ${response.statusCode}
Response message: ${response.statusMessage}
`,
)
reject(err)
// status codes here are all 2xx
} else {
// We only enable this pipe connection when we know we've got a successful return
// and handle the completion with verify and resolve
// there was a possible race condition between end of request and close of writeStream
// that is made ordered with this Promise.all
Promise.all([new Promise((r) => {
return response.pipe(fs.createWriteStream(downloadDestination).on('close', r))
}), new Promise((r) => response.on('end', r))])
.then(() => {
debug('downloading finished')
verifyDownloadedFile(downloadDestination, expectedSize,
expectedChecksum)
.then(() => debug('verified'))
.then(() => resolve(version))
.catch(reject)
})
}
})
.on('error', (e) => {
if (e.code === 'ECONNRESET') return // sometimes proxies give ECONNRESET but we don't care
reject(e)
})
.on('progress', (state) => {
// total time we've elapsed
// starting on our first progress notification
const elapsed = new Date() - started
// request-progress sends a value between 0 and 1
const percentage = util.convertPercentToPercentage(state.percent)
const eta = util.calculateEta(percentage, elapsed)
// send up our percent and seconds remaining
progress.onProgress(percentage, util.secsRemaining(eta))
})
})
}
/**
* Download Cypress.zip from external versionUrl to local file.
* @param [string] version Could be "3.3.0" or full URL
* @param [string] downloadDestination Local filename to save as
*/
const start = async (opts) => {
let { version, downloadDestination, progress, redirectTTL } = opts
if (!downloadDestination) {
la(is.unemptyString(downloadDestination), 'missing download dir', opts)
}
if (!progress) {
progress = { onProgress: () => {
return {}
} }
}
const arch = await util.getRealArch()
const versionUrl = getUrl(arch, version)
progress.throttle = 100
debug('needed Cypress version: %s', version)
debug('source url %s', versionUrl)
debug(`downloading cypress.zip to "${downloadDestination}"`)
// ensure download dir exists
return fs.ensureDirAsync(path.dirname(downloadDestination))
.then(() => {
return getCA()
})
.then((ca) => {
return downloadFromUrl({ url: versionUrl, downloadDestination, progress, ca, version,
...(redirectTTL ? { redirectTTL } : {}) })
})
.catch((err) => {
return prettyDownloadErr(err, versionUrl)
})
}
module.exports = {
start,
getUrl,
getProxyForUrlWithNpmConfig,
getCA,
}
| cypress/cli/lib/tasks/download.js/0 | {
"file_path": "cypress/cli/lib/tasks/download.js",
"repo_id": "cypress",
"token_count": 3883
} | 13 |
#!/usr/bin/env node
const { includeTypes } = require('./utils')
const { join } = require('path')
const shell = require('shelljs')
shell.set('-v') // verbose
shell.set('-e') // any error is fatal
shell.rm('-rf', 'build')
shell.mkdir('-p', 'build/bin')
shell.mkdir('-p', 'build/types')
shell.cp('bin/cypress', 'build/bin/cypress')
shell.cp('NPM_README.md', 'build/README.md')
shell.cp('.release.json', 'build/.release.json')
// copies our typescript definitions
shell.cp('-R', 'types/*.ts', 'build/types/')
// copies 3rd party typescript definitions
includeTypes.forEach((folder) => {
const source = join('types', folder)
shell.cp('-R', source, 'build/types')
})
// TODO: Add a typescript or rollup build step
// The only reason start-build.js exists
// is because the cli package does not have an actual
// build process to compile index.js and lib
shell.exec('babel lib -d build/lib')
shell.exec('babel index.js -o build/index.js')
shell.cp('index.mjs', 'build/index.mjs')
| cypress/cli/scripts/start-build.js/0 | {
"file_path": "cypress/cli/scripts/start-build.js",
"repo_id": "cypress",
"token_count": 342
} | 14 |
require('../../spec_helper')
const _ = require('lodash')
const cp = require('child_process')
const os = require('os')
const tty = require('tty')
const path = require('path')
const EE = require('events')
const mockedEnv = require('mocked-env')
const debug = require('debug')('test')
const state = require(`${lib}/tasks/state`)
const xvfb = require(`${lib}/exec/xvfb`)
const spawn = require(`${lib}/exec/spawn`)
const verify = require(`${lib}/tasks/verify`)
const util = require(`${lib}/util.js`)
const expect = require('chai').expect
const snapshot = require('../../support/snapshot')
const cwd = process.cwd()
const execPath = process.execPath
const nodeVersion = process.versions.node
const defaultBinaryDir = '/default/binary/dir'
describe('lib/exec/spawn', function () {
beforeEach(function () {
os.platform.returns('darwin')
sinon.stub(process, 'exit')
this.spawnedProcess = {
on: sinon.stub().returns(undefined),
unref: sinon.stub().returns(undefined),
stdin: {
on: sinon.stub().returns(undefined),
pipe: sinon.stub().returns(undefined),
},
stdout: {
on: sinon.stub().returns(undefined),
pipe: sinon.stub().returns(undefined),
},
stderr: {
pipe: sinon.stub().returns(undefined),
on: sinon.stub().returns(undefined),
},
kill: sinon.stub(),
// expected by sinon
cancel: sinon.stub(),
}
// process.stdin is both an event emitter and a readable stream
this.processStdin = new EE()
this.processStdin.pipe = sinon.stub().returns(undefined)
sinon.stub(process, 'stdin').value(this.processStdin)
sinon.stub(cp, 'spawn').returns(this.spawnedProcess)
sinon.stub(xvfb, 'start').resolves()
sinon.stub(xvfb, 'stop').resolves()
sinon.stub(xvfb, 'isNeeded').returns(false)
sinon.stub(state, 'getBinaryDir').returns(defaultBinaryDir)
sinon.stub(state, 'getPathToExecutable').withArgs(defaultBinaryDir).returns('/path/to/cypress')
})
context('.isGarbageLineWarning', () => {
it('returns true', () => {
const str = `
[46454:0702/140217.292422:ERROR:gles2_cmd_decoder.cc(4439)] [.RenderWorker-0x7f8bc5815a00.GpuRasterization]GL ERROR :GL_INVALID_FRAMEBUFFER_OPERATION : glDrawElements: framebuffer incomplete
[46454:0702/140217.292466:ERROR:gles2_cmd_decoder.cc(17788)] [.RenderWorker-0x7f8bc5815a00.GpuRasterization]GL ERROR :GL_INVALID_OPERATION : glCreateAndConsumeTextureCHROMIUM: invalid mailbox name
[46454:0702/140217.292526:ERROR:gles2_cmd_decoder.cc(4439)] [.RenderWorker-0x7f8bc5815a00.GpuRasterization]GL ERROR :GL_INVALID_FRAMEBUFFER_OPERATION : glClear: framebuffer incomplete
[46454:0702/140217.292555:ERROR:gles2_cmd_decoder.cc(4439)] [.RenderWorker-0x7f8bc5815a00.GpuRasterization]GL ERROR :GL_INVALID_FRAMEBUFFER_OPERATION : glDrawElements: framebuffer incomplete
[46454:0702/140217.292584:ERROR:gles2_cmd_decoder.cc(4439)] [.RenderWorker-0x7f8bc5815a00.GpuRasterization]GL ERROR :GL_INVALID_FRAMEBUFFER_OPERATION : glClear: framebuffer incomplete
[46454:0702/140217.292612:ERROR:gles2_cmd_decoder.cc(4439)] [.RenderWorker-0x7f8bc5815a00.GpuRasterization]GL ERROR :GL_INVALID_FRAMEBUFFER_OPERATION : glDrawElements: framebuffer incomplete'
[1957:0406/160550.146820:ERROR:bus.cc(392)] Failed to connect to the bus: Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory
[1957:0406/160550.147994:ERROR:bus.cc(392)] Failed to connect to the bus: Address does not contain a colon
[3801:0606/152837.383892:ERROR:cert_verify_proc_builtin.cc(681)] CertVerifyProcBuiltin for www.googletagmanager.com failed:
----- Certificate i=0 (OU=Cypress Proxy Server Certificate,O=Cypress Proxy CA,L=Internet,ST=Internet,C=Internet,CN=www.googletagmanager.com) -----
ERROR: No matching issuer found
objc[60540]: Class WebSwapCGLLayer is implemented in both /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/Frameworks/libANGLE-shared.dylib (0x7ffa5a006318) and /{path/to/app}/node_modules/electron/dist/Electron.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries/libGLESv2.dylib (0x10f8a89c8). One of the two will be used. Which one is undefined.
Warning: loader_scanned_icd_add: Driver /usr/lib/x86_64-linux-gnu/libvulkan_intel.so supports Vulkan 1.2, but only supports loader interface version 4. Interface version 5 or newer required to support this version of Vulkan (Policy #LDP_DRIVER_7)
Warning: loader_scanned_icd_add: Driver /usr/lib/x86_64-linux-gnu/libvulkan_lvp.so supports Vulkan 1.1, but only supports loader interface version 4. Interface version 5 or newer required to support this version of Vulkan (Policy #LDP_DRIVER_7)
Warning: loader_scanned_icd_add: Driver /usr/lib/x86_64-linux-gnu/libvulkan_radeon.so supports Vulkan 1.2, but only supports loader interface version 4. Interface version 5 or newer required to support this verison of Vulkan (Policy #LDP_DRIVER_7)
Warning: Layer VK_LAYER_MESA_device_select uses API version 1.2 which is older than the application specified API version of 1.3. May cause issues.
Warning: vkCreateInstance: Found no drivers!
Warning: vkCreateInstance failed with VK_ERROR_INCOMPATIBLE_DRIVER
at CheckVkSuccessImpl (../../third_party/dawn/src/dawn/native/vulkan/VulkanError.cpp:88)
at CreateVkInstance (../../third_party/dawn/src/dawn/native/vulkan/BackendVk.cpp:458)
at Initialize (../../third_party/dawn/src/dawn/native/vulkan/BackendVk.cpp:344)
at Create (../../third_party/dawn/src/dawn/native/vulkan/BackendVk.cpp:266)
at operator() (../../third_party/dawn/src/dawn/native/vulkan/BackendVk.cpp:521)
`
const lines = _
.chain(str)
.split('\n')
.invokeMap('trim')
.compact()
.value()
_.each(lines, (line) => {
expect(spawn.isGarbageLineWarning(line), `expected line to be garbage: ${line}`).to.be.true
})
})
})
context('.start', function () {
// ️️⚠️ NOTE ⚠️
// when asserting the calls made to spawn the child Cypress process
// we have to be _very_ careful. Spawn uses process.env object, if an assertion
// fails, it will print the entire process.env object to the logs, which
// might contain sensitive environment variables. Think about what the
// failed assertion might print to the public CI logs and limit
// the environment variables when running tests on CI.
it('passes args + options to spawn', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
sinon.stub(verify, 'needsSandbox').returns(false)
return spawn.start('--foo', { foo: 'bar' })
.then(() => {
expect(cp.spawn).to.be.calledWithMatch('/path/to/cypress', [
'--',
'--foo',
'--cwd',
cwd,
'--userNodePath',
execPath,
'--userNodeVersion',
nodeVersion,
], {
detached: false,
stdio: ['inherit', 'inherit', 'pipe'],
})
})
})
it('uses --no-sandbox when needed', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
sinon.stub(verify, 'needsSandbox').returns(true)
return spawn.start('--foo', { foo: 'bar' })
.then(() => {
// skip the options argument: we do not need anything about it
// and also less risk that a failed assertion would dump the
// entire ENV object with possible sensitive variables
const args = cp.spawn.firstCall.args.slice(0, 2)
// it is important for "--no-sandbox" to appear before "--" separator
const expectedCliArgs = [
'--no-sandbox',
'--',
'--foo',
'--cwd',
cwd,
'--userNodePath',
execPath,
'--userNodeVersion',
nodeVersion,
]
expect(args).to.deep.equal(['/path/to/cypress', expectedCliArgs])
})
})
it('uses npm command when running in dev mode', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
sinon.stub(verify, 'needsSandbox').returns(false)
const p = path.resolve('..', 'scripts', 'start.js')
return spawn.start('--foo', { dev: true, foo: 'bar' })
.then(() => {
expect(cp.spawn).to.be.calledWithMatch('node', [
p,
'--',
'--foo',
'--cwd',
cwd,
'--userNodePath',
execPath,
'--userNodeVersion',
nodeVersion,
], {
detached: false,
stdio: ['inherit', 'inherit', 'pipe'],
})
})
})
it('does not pass --no-sandbox when running in dev mode', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
sinon.stub(verify, 'needsSandbox').returns(true)
const p = path.resolve('..', 'scripts', 'start.js')
return spawn.start('--foo', { dev: true, foo: 'bar' })
.then(() => {
expect(cp.spawn).to.be.calledWithMatch('node', [
p,
'--',
'--foo',
'--cwd',
cwd,
'--userNodePath',
execPath,
'--userNodeVersion',
nodeVersion,
], {
detached: false,
stdio: ['inherit', 'inherit', 'pipe'],
})
})
})
it('starts xvfb when needed', function () {
xvfb.isNeeded.returns(true)
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
return spawn.start('--foo')
.then(() => {
expect(xvfb.start).to.be.calledOnce
})
})
context('closes', function () {
['close', 'exit'].forEach((event) => {
it(`if '${event}' event fired`, function () {
this.spawnedProcess.on.withArgs(event).yieldsAsync(0)
return spawn.start('--foo')
})
})
it('if exit event fired and close event fired', function () {
this.spawnedProcess.on.withArgs('exit').yieldsAsync(0)
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
return spawn.start('--foo')
})
})
context('detects kill signal', function () {
it('exits with error on SIGKILL', function () {
this.spawnedProcess.on.withArgs('exit').yieldsAsync(null, 'SIGKILL')
return spawn.start('--foo')
.then(() => {
throw new Error('should have hit error handler but did not')
}, (e) => {
debug('error message', e.message)
snapshot(e.message)
})
})
})
it('does not start xvfb when its not needed', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
return spawn.start('--foo')
.then(() => {
expect(xvfb.start).not.to.be.called
})
})
it('stops xvfb when spawn closes', function () {
xvfb.isNeeded.returns(true)
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
this.spawnedProcess.on.withArgs('close').yields()
return spawn.start('--foo')
.then(() => {
expect(xvfb.stop).to.be.calledOnce
})
})
it('resolves with spawned close code in the message', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(10)
return spawn.start('--foo')
.then((code) => {
expect(code).to.equal(10)
})
})
describe('Linux display', () => {
let restore
beforeEach(() => {
restore = mockedEnv({
DISPLAY: 'test-display',
})
})
afterEach(() => {
restore()
})
it('retries with xvfb if fails with display exit code', function () {
this.spawnedProcess.on.withArgs('close').onFirstCall().yieldsAsync(1)
this.spawnedProcess.on.withArgs('close').onSecondCall().yieldsAsync(0)
const buf1 = '[some noise here] Gtk: cannot open display: 987'
this.spawnedProcess.stderr.on
.withArgs('data')
.yields(buf1)
os.platform.returns('linux')
return spawn.start('--foo')
.then((code) => {
expect(xvfb.start).to.have.been.calledOnce
expect(xvfb.stop).to.have.been.calledOnce
expect(cp.spawn).to.have.been.calledTwice
// second code should be 0 after successfully running with Xvfb
expect(code).to.equal(0)
})
})
})
it('rejects with error from spawn', function () {
const msg = 'the error message'
this.spawnedProcess.on.withArgs('error').yieldsAsync(new Error(msg))
return spawn.start('--foo')
.then(() => {
throw new Error('should have hit error handler but did not')
}, (e) => {
debug('error message', e.message)
expect(e.message).to.include(msg)
})
})
it('unrefs if options.detached is true', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
return spawn.start(null, { detached: true })
.then(() => {
expect(this.spawnedProcess.unref).to.be.calledOnce
})
})
it('does not unref by default', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
return spawn.start()
.then(() => {
expect(this.spawnedProcess.unref).not.to.be.called
})
})
it('sets process.env to options.env', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
process.env.FOO = 'bar'
return spawn.start()
.then(() => {
expect(cp.spawn.firstCall.args[2].env.FOO).to.eq('bar')
})
})
it('forces colors and streams when supported', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
sinon.stub(util, 'supportsColor').returns(true)
sinon.stub(tty, 'isatty').returns(true)
return spawn.start([], { env: {} })
.then(() => {
snapshot(cp.spawn.firstCall.args[2].env)
})
})
it('sets windowsHide:false property in windows', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
os.platform.returns('win32')
return spawn.start([], { env: {} })
.then(() => {
expect(cp.spawn.firstCall.args[2].windowsHide).to.be.false
})
})
it('does not set windowsHide property when in darwin', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
return spawn.start([], { env: {} })
.then(() => {
expect(cp.spawn.firstCall.args[2].windowsHide).to.be.undefined
})
})
it('does not force colors and streams when not supported', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
sinon.stub(util, 'supportsColor').returns(false)
sinon.stub(tty, 'isatty').returns(false)
return spawn.start([], { env: {} })
.then(() => {
snapshot(cp.spawn.firstCall.args[2].env)
})
})
it('pipes when on win32', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
os.platform.returns('win32')
xvfb.isNeeded.returns(false)
return spawn.start()
.then(() => {
expect(cp.spawn.firstCall.args[2].stdio).to.deep.eq('pipe')
// parent process STDIN was piped to child process STDIN
expect(this.processStdin.pipe, 'process.stdin').to.have.been.calledOnce
.and.to.have.been.calledWith(this.spawnedProcess.stdin)
})
})
it('inherits when on linux and xvfb isn\'t needed', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
os.platform.returns('linux')
xvfb.isNeeded.returns(false)
return spawn.start()
.then(() => {
expect(cp.spawn.firstCall.args[2].stdio).to.deep.eq('inherit')
})
})
it('uses [inherit, inherit, pipe] when linux and xvfb is needed', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
xvfb.isNeeded.returns(true)
os.platform.returns('linux')
return spawn.start()
.then(() => {
expect(cp.spawn.firstCall.args[2].stdio).to.deep.eq([
'inherit', 'inherit', 'pipe',
])
})
})
it('uses [inherit, inherit, pipe] on darwin', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
xvfb.isNeeded.returns(false)
os.platform.returns('darwin')
return spawn.start()
.then(() => {
expect(cp.spawn.firstCall.args[2].stdio).to.deep.eq([
'inherit', 'inherit', 'pipe',
])
})
})
it('writes everything on win32', function () {
const buf1 = Buffer.from('asdf')
this.spawnedProcess.stdin.pipe.withArgs(process.stdin)
this.spawnedProcess.stdout.pipe.withArgs(process.stdout)
this.spawnedProcess.stderr.on
.withArgs('data')
.yields(buf1)
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
sinon.stub(process.stderr, 'write').withArgs(buf1)
os.platform.returns('win32')
return spawn.start()
})
it('does not write to process.stderr when from xlib or libudev', function () {
const buf1 = Buffer.from('Xlib: something foo')
const buf2 = Buffer.from('libudev something bar')
const buf3 = Buffer.from('asdf')
this.spawnedProcess.stderr.on
.withArgs('data')
.onFirstCall()
.yields(buf1)
.onSecondCall()
.yields(buf2)
.onThirdCall()
.yields(buf3)
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
sinon.stub(process.stderr, 'write').withArgs(buf3)
os.platform.returns('linux')
xvfb.isNeeded.returns(true)
return spawn.start()
.then(() => {
expect(process.stderr.write).not.to.be.calledWith(buf1)
expect(process.stderr.write).not.to.be.calledWith(buf2)
})
})
it('does not write to process.stderr when from high sierra warnings', function () {
const buf1 = Buffer.from('2018-05-19 15:30:30.287 Cypress[7850:32145] *** WARNING: Textured Window')
const buf2 = Buffer.from('asdf')
this.spawnedProcess.stderr.on
.withArgs('data')
.onFirstCall()
.yields(buf1)
.onSecondCall(buf2)
.yields(buf2)
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
sinon.stub(process.stderr, 'write').withArgs(buf2)
os.platform.returns('darwin')
return spawn.start()
.then(() => {
expect(process.stderr.write).not.to.be.calledWith(buf1)
})
})
// https://github.com/cypress-io/cypress/issues/1841
// https://github.com/cypress-io/cypress/issues/5241
;['EPIPE', 'ENOTCONN'].forEach((errCode) => {
it(`catches process.stdin errors and returns when code=${errCode}`, function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
return spawn.start()
.then(() => {
let called = false
const fn = () => {
called = true
const err = new Error()
err.code = errCode
return process.stdin.emit('error', err)
}
expect(fn).not.to.throw()
expect(called).to.be.true
})
})
})
it('throws process.stdin errors code!=EPIPE', function () {
this.spawnedProcess.on.withArgs('close').yieldsAsync(0)
return spawn.start()
.then(() => {
const fn = () => {
const err = new Error('wattttt')
err.code = 'FAILWHALE'
return process.stdin.emit('error', err)
}
expect(fn).to.throw(/wattttt/)
})
})
})
})
| cypress/cli/test/lib/exec/spawn_spec.js/0 | {
"file_path": "cypress/cli/test/lib/exec/spawn_spec.js",
"repo_id": "cypress",
"token_count": 8597
} | 15 |
const spawnMock = require('spawn-mock')
module.exports = {
mockSpawn (cb) {
return spawnMock.mockSpawn((cp) => {
// execa expects .cancel to exist
cp.cancel = sinon.stub()
return cb(cp)
})
},
}
| cypress/cli/test/support/spawn-mock.js/0 | {
"file_path": "cypress/cli/test/support/spawn-mock.js",
"repo_id": "cypress",
"token_count": 100
} | 16 |
namespace CypressLodashTests {
Cypress._ // $ExpectType LoDashStatic
Cypress._.each([1], item => {
item // $ExpectType number
})
}
namespace CypressSinonTests {
Cypress.sinon // $ExpectType SinonStatic
const stub = cy.stub()
stub(2, 'foo')
expect(stub).to.have.been.calledWith(Cypress.sinon.match.number, Cypress.sinon.match('foo'))
const stub2 = Cypress.sinon.stub()
stub2(2, 'foo')
expect(stub2).to.have.been.calledWith(Cypress.sinon.match.number, Cypress.sinon.match('foo'))
}
namespace CypressJqueryTests {
Cypress.$ // $ExpectType JQueryStatic
Cypress.$('selector') // $ExpectType JQuery<HTMLElement>
Cypress.$('selector').click() // $ExpectType JQuery<HTMLElement>
}
namespace CypressAutomationTests {
Cypress.automation('hello') // $ExpectType Promise<any>
}
namespace CypressConfigTests {
// getters
Cypress.config('baseUrl') // $ExpectType string | null
Cypress.config().baseUrl // $ExpectType string | null
// setters
Cypress.config('baseUrl', '.') // $ExpectType void
Cypress.config({ e2e: { baseUrl: '.' } }) // $ExpectError
Cypress.config({ e2e: { baseUrl: null } }) // $ExpectError
Cypress.config({ e2e: { baseUrl: '.', } }) // $ExpectError
Cypress.config({ component: { baseUrl: '.', devServer: () => ({} as any) } }) // $ExpectError
Cypress.config({ e2e: { indexHtmlFile: 'index.html' } }) // $ExpectError
Cypress.config({ testIsolation: false }) // $ExpectError
Cypress.config('taskTimeout') // $ExpectType number
Cypress.config('includeShadowDom') // $ExpectType boolean
}
namespace CypressEnvTests {
// Just making sure these are valid - no real type safety
Cypress.env('foo')
Cypress.env('foo', 'bar')
Cypress.env().foo
Cypress.env({
foo: 'bar'
})
}
namespace CypressIsCyTests {
Cypress.isCy(cy) // $ExpectType boolean
Cypress.isCy(undefined) // $ExpectType boolean
const chainer = cy.wrap("foo").then(function() {
if (Cypress.isCy(chainer)) {
chainer // $ExpectType Chainable<string>
}
})
}
declare namespace Cypress {
interface Chainable {
newCommand: (arg: string) => Chainable<number>
newQuery: (arg: string) => Chainable<number>
}
}
namespace CypressCommandsTests {
Cypress.Commands.add('newCommand', (arg) => {
// $ExpectType string
arg
return
})
Cypress.Commands.add('newCommand', (arg) => {
// $ExpectType string
arg
})
Cypress.Commands.add('newCommand', function(arg) {
this // $ExpectType Context
arg // $ExpectType string
})
Cypress.Commands.add('newCommand', { prevSubject: true }, (subject, arg) => {
subject // $ExpectType any
arg // $ExpectType string
return
})
Cypress.Commands.add('newCommand', { prevSubject: false }, (arg: string) => {
arg // $ExpectType string
return
})
Cypress.Commands.add('newCommand', { prevSubject: 'optional' }, (subject, arg) => {
subject // $ExpectType unknown
arg // $ExpectType string
return
})
Cypress.Commands.add('newCommand', { prevSubject: 'optional' }, (subject, arg) => {
subject // $ExpectType unknown
arg // $ExpectType string
})
Cypress.Commands.add('newCommand', { prevSubject: ['optional'] }, (subject, arg) => {
subject // $ExpectType unknown
arg // $ExpectType string
})
Cypress.Commands.add('newCommand', { prevSubject: 'document' }, (subject, arg) => {
subject // $ExpectType Document
arg // $ExpectType string
})
Cypress.Commands.add('newCommand', { prevSubject: 'window' }, (subject, arg) => {
subject // $ExpectType Window
arg // $ExpectType string
})
Cypress.Commands.add('newCommand', { prevSubject: 'element' }, (subject, arg) => {
subject // $ExpectType JQueryWithSelector<HTMLElement>
arg // $ExpectType string
})
Cypress.Commands.add('newCommand', { prevSubject: ['element'] }, (subject, arg) => {
subject // $ExpectType JQueryWithSelector<HTMLElement>
arg // $ExpectType string
})
Cypress.Commands.add('newCommand', { prevSubject: ['element', 'document', 'window'] }, (subject, arg) => {
if (subject instanceof Window) {
subject // $ExpectType Window
} else if (subject instanceof Document) {
subject // $ExpectType Document
} else {
subject // $ExpectType JQueryWithSelector<HTMLElement>
}
arg // $ExpectType string
})
Cypress.Commands.add('newCommand', { prevSubject: ['window', 'document', 'optional', 'element'] }, (subject, arg) => {
if (subject instanceof Window) {
subject // $ExpectType Window
} else if (subject instanceof Document) {
subject // $ExpectType Document
} else if (subject) {
subject // $ExpectType JQueryWithSelector<HTMLElement>
} else {
subject // $ExpectType void
}
arg // $ExpectType string
})
Cypress.Commands.add('newCommand', (arg) => {
// $ExpectType string
arg
return cy.wrap(new Promise<number>((resolve) => { resolve(5) }))
})
Cypress.Commands.addAll({
newCommand(arg) {
// $ExpectType any
arg
this // $ExpectType Context
return
},
newCommand2(arg, arg2) {
// $ExpectType any
arg
// $ExpectType any
arg2
},
newCommand3: (arg) => {
// $ExpectType any
arg
return
},
newCommand4: (arg) => {
// $ExpectType any
arg
},
})
Cypress.Commands.addAll({ prevSubject: true }, {
newCommand: (subject, arg) => {
subject // $ExpectType any
arg // $ExpectType any
return
},
})
Cypress.Commands.addAll({ prevSubject: false }, {
newCommand: (arg) => {
arg // $ExpectType any
return
},
})
Cypress.Commands.addAll({ prevSubject: 'optional' }, {
newCommand: (subject, arg) => {
subject // $ExpectType unknown
arg // $ExpectType any
return
},
newCommand2: (subject, arg) => {
subject // $ExpectType unknown
arg // $ExpectType any
},
})
Cypress.Commands.addAll({ prevSubject: ['optional'] }, {
newCommand: (subject, arg) => {
subject // $ExpectType unknown
arg // $ExpectType any
},
})
Cypress.Commands.addAll({ prevSubject: 'document' }, {
newCommand: (subject, arg) => {
subject // $ExpectType Document
arg // $ExpectType any
},
})
Cypress.Commands.addAll({ prevSubject: 'window' }, {
newCommand: (subject, arg) => {
subject // $ExpectType Window
arg // $ExpectType any
},
})
Cypress.Commands.addAll({ prevSubject: 'element' }, {
newCommand: (subject, arg) => {
subject // $ExpectType JQueryWithSelector<HTMLElement>
arg // $ExpectType any
}
})
Cypress.Commands.addAll({ prevSubject: ['element'] }, {
newCommand: (subject, arg) => {
subject // $ExpectType JQueryWithSelector<HTMLElement>
arg // $ExpectType any
}
})
Cypress.Commands.addAll({ prevSubject: ['element', 'document', 'window'] }, {
newCommand: (subject, arg) => {
if (subject instanceof Window) {
subject // $ExpectType Window
} else if (subject instanceof Document) {
subject // $ExpectType Document
} else {
subject // $ExpectType JQueryWithSelector<HTMLElement>
}
arg // $ExpectType any
}
})
Cypress.Commands.addAll({ prevSubject: ['window', 'document', 'optional', 'element'] }, {
newCommand: (subject, arg) => {
if (subject instanceof Window) {
subject // $ExpectType Window
} else if (subject instanceof Document) {
subject // $ExpectType Document
} else if (subject) {
subject // $ExpectType JQueryWithSelector<HTMLElement>
} else {
subject // $ExpectType void
}
arg // $ExpectType any
}
})
Cypress.Commands.addAll({
newCommand: (arg) => {
// $ExpectType any
arg
return cy.wrap(new Promise<number>((resolve) => { resolve(5) }))
}
})
Cypress.Commands.overwrite('newCommand', (originalFn, arg) => {
arg // $ExpectType string
originalFn // $ExpectedType Chainable['newCommand']
originalFn(arg) // $ExpectType Chainable<number>
})
Cypress.Commands.overwrite('newCommand', function(originalFn, arg) {
this // $ExpectType Context
arg // $ExpectType string
originalFn // $ExpectedType Chainable['newCommand']
originalFn.apply(this, [arg]) // $ExpectType Chainable<number>
})
Cypress.Commands.overwrite<'type', 'element'>('type', (originalFn, element, text, options?: Partial<Cypress.TypeOptions & { sensitive: boolean }>) => {
element // $ExpectType JQueryWithSelector<HTMLElement>
text // $ExpectType string
if (options && options.sensitive) {
// turn off original log
options.log = false
// create our own log with masked message
Cypress.log({
$el: element,
name: 'type',
message: '*'.repeat(text.length),
})
}
return originalFn(element, text, options)
})
Cypress.Commands.overwrite<'screenshot', 'element'>('screenshot', (originalFn, subject, fileName, options) => {
subject // $ExpectType JQueryWithSelector<HTMLElement>
fileName // $ExpectType string
options // $ExpectType Partial<Loggable & Timeoutable & ScreenshotOptions> | undefined
})
Cypress.Commands.addQuery('newQuery', function(arg) {
this // $ExpectType Command
arg // $ExpectType string
return () => 3
})
}
namespace CypressNowTest {
cy.now('get') // $ExpectType Promise<any> | ((subject: any) => any)
}
namespace CypressEnsuresTest {
Cypress.ensure.isType('', ['optional', 'element'], 'newQuery', cy) // $ExpectType void
Cypress.ensure.isElement('', 'newQuery', cy) // $ExpectType void
Cypress.ensure.isWindow('', 'newQuery', cy) // $ExpectType void
Cypress.ensure.isDocument('', 'newQuery', cy) // $ExpectType void
Cypress.ensure.isAttached('', 'newQuery', cy) // $ExpectType void
Cypress.ensure.isNotDisabled('', 'newQuery') // $ExpectType void
Cypress.ensure.isVisible('', 'newQuery') // $ExpectType void
}
namespace CypressLogsTest {
const log = Cypress.log({
$el: Cypress.$('body'),
name: 'MyCommand',
displayName: 'My Command',
message: ['foo', 'bar'],
consoleProps: () => {
return {
foo: 'bar',
}
},
})
.set('$el', Cypress.$('body'))
.set({ name: 'MyCommand' })
.snapshot()
.snapshot('before')
.snapshot('before', { next: 'after' })
log.get() // $ExpectType LogConfig
log.get('name') // $ExpectType string
log.get('$el') // $ExpectType JQuery<HTMLElement>
}
namespace CypressLocalStorageTest {
Cypress.LocalStorage.clear = function(keys) {
keys // $ExpectType string[] | undefined
}
}
namespace CypressItsTests {
cy.wrap({ foo: [1, 2, 3] })
.its('foo')
.each((s: number) => {
s
})
cy.wrap({ foo: 'bar' }).its('foo') // $ExpectType Chainable<string>
cy.wrap([1, 2]).its(1) // $ExpectType Chainable<number>
cy.wrap(['foo', 'bar']).its(1) // $ExpectType Chainable<string>
.then((s: string) => {
s
})
cy.wrap({ baz: { quux: '2' } }).its('baz.quux') // $ExpectType Chainable<any>
cy.wrap({ foo: 'bar' }).its('foo', { log: true }) // $ExpectType Chainable<string>
cy.wrap({ foo: 'bar' }).its('foo', { timeout: 100 }) // $ExpectType Chainable<string>
cy.wrap({ foo: 'bar' }).its('foo', { log: true, timeout: 100 }) // $ExpectType Chainable<string>
}
namespace CypressInvokeTests {
const returnsString = () => 'foo'
const returnsNumber = () => 42
cy.wrap({ a: returnsString }).invoke('a') // $ExpectType Chainable<string>
cy.wrap({ b: returnsNumber }).invoke('b') // $ExpectType Chainable<number>
cy.wrap({ b: returnsNumber }).invoke({ log: true }, 'b') // $ExpectType Chainable<number>
cy.wrap({ b: returnsNumber }).invoke({ timeout: 100 }, 'b') // $ExpectType Chainable<number>
cy.wrap({ b: returnsNumber }).invoke({ log: true, timeout: 100 }, 'b') // $ExpectType Chainable<number>
// challenging to define a more precise return type than string | number here
cy.wrap([returnsString, returnsNumber]).invoke(1) // $ExpectType Chainable<string | number>
// invoke through property path results in any
cy.wrap({ a: { fn: (x: number) => x * x } }).invoke('a.fn', 4) // $ExpectType Chainable<any>
// examples below are from previous attempt at typing `invoke`
// (see https://github.com/cypress-io/cypress/issues/4022)
// call methods on arbitrary objects with reasonable return types
cy.wrap({ fn: () => ({ a: 1 }) }).invoke("fn") // $ExpectType Chainable<{ a: number; }>
// call methods on dom elements with reasonable return types
cy.get('.trigger-input-range').invoke('val', 25) // $ExpectType Chainable<string | number | string[] | undefined>
}
cy.wrap({ foo: ['bar', 'baz'] })
.its('foo')
.then(([first, second]) => {
first // $ExpectType string
})
.spread((first: string, second: string) => {
first // $ExpectType string
// return first as string
})
.each((s: string) => {
s // $ExpectType string
})
.then(s => {
s // $ExpectType string[]
})
cy.get('.someSelector')
.each(($el, index, list) => {
$el // $ExpectType JQuery<HTMLElement>
index // $ExpectType number
list // $ExpectType HTMLElement[]
})
cy.wrap(['bar', 'baz'])
.spread((first, second) => {
first // $ExpectType any
})
describe('then', () => {
// https://github.com/cypress-io/cypress/issues/5575
it('should respect the return type of callback', () => {
// Expected type is verbose here because the function below matches 2 declarations.
// * then<S extends object | any[] | string | number | boolean>(fn: (this: ObjectLike, currentSubject: Subject) => S): Chainable<S>
// * then<S>(fn: (this: ObjectLike, currentSubject: Subject) => S): ThenReturn<Subject, S>
// For our purpose, it doesn't matter.
const result = cy.get('foo').then(el => el.attr('foo'))
result // $ExpectType Chainable<JQuery<HTMLElement>> | Chainable<string | JQuery<HTMLElement>>
const result2 = cy.get('foo').then(el => `${el}`)
result2 // $ExpectType Chainable<string>
const result3 = cy.get('foo').then({ timeout: 1234 }, el => el.attr('foo'))
result3 // $ExpectType Chainable<JQuery<HTMLElement>> | Chainable<string | JQuery<HTMLElement>>
const result4 = cy.get('foo').then({ timeout: 1234 }, el => `${el}`)
result4 // $ExpectType Chainable<string>
})
it('should have the correct type signature', () => {
cy.wrap({ foo: 'bar' })
.then(s => {
s // $ExpectType { foo: string; }
return s
})
.then(s => {
s // $ExpectType { foo: string; }
})
.then(s => s.foo)
.then(s => {
s // $ExpectType string
})
})
it('should have the correct type signature with options', () => {
cy.wrap({ foo: 'bar' })
.then({ timeout: 5000 }, s => {
s // $ExpectType { foo: string; }
return s
})
.then({ timeout: 5000 }, s => {
s // $ExpectType { foo: string; }
})
.then({ timeout: 5000 }, s => s.foo)
.then({ timeout: 5000 }, s => {
s // $ExpectType string
})
})
it('HTMLElement', () => {
cy.get('div')
.then(($div) => {
$div // $ExpectType JQuery<HTMLDivElement>
return $div[0]
})
.then(($div) => {
$div // $ExpectType JQuery<HTMLDivElement>
})
cy.get('div')
.then(($div) => {
$div // $ExpectType JQuery<HTMLDivElement>
return [$div[0]]
})
.then(($div) => {
$div // $ExpectType JQuery<HTMLDivElement>
})
cy.get('p')
.then(($p) => {
$p // $ExpectType JQuery<HTMLParagraphElement>
return $p[0]
})
.then({ timeout: 3000 }, ($p) => {
$p // $ExpectType JQuery<HTMLParagraphElement>
})
})
// https://github.com/cypress-io/cypress/issues/16669
it('any as default', () => {
cy.get('body')
.then(() => ({} as any))
.then(v => {
v // $ExpectType any
})
})
})
cy.wait(['@foo', '@bar'])
.then(([first, second]) => {
first // $ExpectType Interception<any, any>
})
cy.wait(1234) // $ExpectType Chainable<undefined>
cy.wrap('foo').wait(1234) // $ExpectType Chainable<string>
cy.wrap([{ foo: 'bar' }, { foo: 'baz' }])
.then(subject => {
subject // $ExpectType { foo: string; }[]
})
.then(([first, second]) => {
first // $ExpectType { foo: string; }
})
.then(subject => {
subject // $ExpectType { foo: string; }[]
})
.then(([first, second]) => {
return first.foo + second.foo
})
.then(subject => {
subject // $ExpectType string
})
cy.wrap([1, 2, 3]).each((num: number, i, array) => {
return new Cypress.Promise((resolve) => {
setTimeout(() => {
resolve()
}, num * 100)
})
})
cy.get('something').should('have.length', 1)
cy.stub().withArgs('').log(false).as('foo')
cy.spy().withArgs('').log(false).as('foo')
cy.get('something').as('foo', { type: 'static' })
cy.wrap('foo').then(subject => {
subject // $ExpectType string
return cy.wrap(subject)
}).then(subject => {
subject // $ExpectType string
})
cy.wrap('foo').then(subject => {
subject // $ExpectType string
return Cypress.Promise.resolve(subject)
}).then(subject => {
subject // $ExpectType string
})
cy.get('body').within(body => {
body // $ExpectType JQuery<HTMLBodyElement>
})
cy.get('body').within({ log: false }, body => {
body // $ExpectType JQuery<HTMLBodyElement>
})
cy.get('body').within(() => {
cy.get('body', { withinSubject: null }).then(body => {
body // $ExpectType JQuery<HTMLBodyElement>
})
})
cy
.get('body')
.then(() => {
return cy.wrap(undefined)
})
.then(subject => {
subject // $ExpectType undefined
})
namespace CypressAUTWindowTests {
cy.go(2).then((win) => {
win // $ExpectType AUTWindow
})
cy.reload().then((win) => {
win // $ExpectType AUTWindow
})
cy.visit('https://google.com').then(win => {
win // $ExpectType AUTWindow
})
cy.window().then(win => {
win // $ExpectType AUTWindow
})
}
namespace CypressOnTests {
Cypress.on('uncaught:exception', (error, runnable, promise) => {
error // $ExpectType Error
runnable // $ExpectType Runnable
promise // $ExpectType Promise<any> | undefined
})
cy.on('uncaught:exception', (error, runnable, promise) => {
error // $ExpectType Error
runnable // $ExpectType Runnable
promise // $ExpectType Promise<any> | undefined
})
// you can chain multiple callbacks
Cypress
.on('test:before:run', () => { })
.on('test:after:run', () => { })
.on('test:before:run:async', () => { })
cy
.on('window:before:load', () => { })
.on('command:start', () => { })
}
namespace CypressOnceTests {
Cypress.once('uncaught:exception', (error, runnable) => {
error // $ExpectType Error
runnable // $ExpectType Runnable
})
cy.once('uncaught:exception', (error, runnable) => {
error // $ExpectType Error
runnable // $ExpectType Runnable
})
}
namespace CypressOffTests {
Cypress.off('uncaught:exception', (error, runnable) => {
error // $ExpectType Error
runnable // $ExpectType Runnable
})
cy.off('uncaught:exception', (error, runnable) => {
error // $ExpectType Error
runnable // $ExpectType Runnable
})
}
namespace CypressFilterTests {
cy.get<HTMLDivElement>('#id')
.filter((index: number, element: HTMLDivElement) => {
index // $ExpectType number
element // $ExpectType HTMLDivElement
return true
})
}
namespace CypressScreenshotTests {
cy.screenshot().then((result) => {
result // $ExpectType undefined
})
cy.screenshot('example-name')
cy.screenshot('example', { log: false })
cy.screenshot({ log: false })
cy.screenshot({
log: true,
blackout: []
})
cy.screenshot('example', {
log: true,
blackout: []
})
cy.get<HTMLDivElement>('#id').screenshot('example-name', { log: false })
cy.get<HTMLDivElement>('#id').screenshot().then((result) => {
result // $ExpectType JQuery<HTMLDivElement>
})
}
namespace CypressShadowDomTests {
cy.get('my-component').shadow()
}
namespace CypressTriggerTests {
cy.get('something')
.trigger('click') // .trigger(eventName)
.trigger('click', 'center') // .trigger(eventName, position)
.trigger('click', { // .trigger(eventName, options)
arbitraryProperty: 0
})
.trigger('click', 0, 0) // .trigger(eventName, x, y)
.trigger('click', 'center', { // .trigger(eventName, position, options)
arbitraryProperty: 0
})
.trigger('click', 0, 0, { // .trigger(eventName, x, y, options)
arbitraryProperty: 0
})
}
namespace CypressClockTests {
// timestamp
cy.clock(new Date(2019, 3, 2).getTime(), ['Date'])
// timestamp shortcut
cy.clock(+ new Date(), ['Date'])
// Date object
cy.clock(new Date(2019, 3, 2))
// restoring the clock
cy.clock().then(clock => {
clock.restore()
})
// restoring the clock shortcut
cy.clock().invoke('restore')
// setting system time with no argument
cy.clock().then(clock => {
clock.setSystemTime()
})
// setting system time with timestamp
cy.clock().then(clock => {
clock.setSystemTime(1000)
})
// setting system time with date object
cy.clock().then(clock => {
clock.setSystemTime(new Date(2019, 3, 2))
})
// setting system time with no argument and shortcut
cy.clock().invoke('setSystemTime')
// setting system time with timestamp and shortcut
cy.clock().invoke('setSystemTime', 1000)
// setting system time with date object and shortcut
cy.clock().invoke('setSystemTime', new Date(2019, 3, 2))
}
namespace CypressContainsTests {
cy.contains('#app')
cy.contains('my text to find')
cy.contains('#app', 'my text to find')
cy.contains('#app', 'my text to find', { log: false, timeout: 100, matchCase: false, includeShadowDom: true })
cy.contains('my text to find', { log: false, timeout: 100, matchCase: false, includeShadowDom: true })
}
// https://github.com/cypress-io/cypress/pull/5574
namespace CypressLocationTests {
cy.location('path') // $ExpectError
cy.location('pathname') // $ExpectType Chainable<string>
}
// https://github.com/cypress-io/cypress/issues/17399
namespace CypressUrlTests {
cy.url({ decode: true }).should('contain', '사랑')
}
namespace CypressBrowserTests {
Cypress.isBrowser('chrome')// $ExpectType boolean
Cypress.isBrowser('firefox')// $ExpectType boolean
Cypress.isBrowser('edge')// $ExpectType boolean
Cypress.isBrowser('brave')// $ExpectType boolean
// does not error to allow for user supplied browsers
Cypress.isBrowser('safari')// $ExpectType boolean
Cypress.isBrowser({ channel: 'stable' })// $ExpectType boolean
Cypress.isBrowser({ family: 'chromium' })// $ExpectType boolean
Cypress.isBrowser({ name: 'chrome' })// $ExpectType boolean
Cypress.isBrowser({ family: 'foo' }) // $ExpectError
Cypress.isBrowser() // $ExpectError
}
namespace CypressDomTests {
const obj: any = {}
const el = {} as any as HTMLElement
const jel = {} as any as JQuery
const doc = {} as any as Document
Cypress.dom.wrap((x: number) => 'a') // $ExpectType JQuery<HTMLElement>
Cypress.dom.query('foo', el) // $ExpectType JQuery<HTMLElement>
Cypress.dom.unwrap(obj) // $ExpectType any
Cypress.dom.isDom(obj) // $ExpectType boolean
Cypress.dom.isType(el, 'foo') // $ExpectType boolean
Cypress.dom.isVisible(el) // $ExpectType boolean
Cypress.dom.isHidden(el) // $ExpectType boolean
Cypress.dom.isFocusable(el) // $ExpectType boolean
Cypress.dom.isTextLike(el) // $ExpectType boolean
Cypress.dom.isScrollable(el) // $ExpectType boolean
Cypress.dom.isFocused(el) // $ExpectType boolean
Cypress.dom.isDetached(el) // $ExpectType boolean
Cypress.dom.isAttached(el) // $ExpectType boolean
Cypress.dom.isSelector(el, 'foo') // $ExpectType boolean
Cypress.dom.isDescendent(el, el) // $ExpectType boolean
Cypress.dom.isElement(obj) // $ExpectType boolean
Cypress.dom.isDocument(obj) // $ExpectType boolean
Cypress.dom.isWindow(obj) // $ExpectType boolean
Cypress.dom.isJquery(obj) // $ExpectType boolean
Cypress.dom.isInputType(el, 'number') // $ExpectType boolean
Cypress.dom.stringify(el, 'foo') // $ExpectType string
Cypress.dom.getElements(jel) // $ExpectType JQuery<HTMLElement> | HTMLElement[]
Cypress.dom.getContainsSelector('foo', 'bar') // $ExpectType string
Cypress.dom.getContainsSelector('foo', 'bar', { matchCase: true }) // $ExpectType string
Cypress.dom.getFirstDeepestElement([el], 1) // $ExpectType HTMLElement
Cypress.dom.getWindowByElement(el) // $ExpectType HTMLElement | JQuery<HTMLElement>
Cypress.dom.getReasonIsHidden(el) // $ExpectType string
Cypress.dom.getFirstScrollableParent(el) // $ExpectType HTMLElement | JQuery<HTMLElement>
Cypress.dom.getFirstFixedOrStickyPositionParent(el) // $ExpectType HTMLElement | JQuery<HTMLElement>
Cypress.dom.getFirstStickyPositionParent(el) // $ExpectType HTMLElement | JQuery<HTMLElement>
Cypress.dom.getCoordsByPosition(1, 2) // $ExpectType number
Cypress.dom.getElementPositioning(el) // $ExpectType ElementPositioning
Cypress.dom.getElementAtPointFromViewport(doc, 1, 2) // $ExpectType Element | null
Cypress.dom.getElementCoordinatesByPosition(el, 'top') // $ExpectType ElementCoordinates
Cypress.dom.getElementCoordinatesByPositionRelativeToXY(el, 1, 2) // $ExpectType ElementPositioning
Cypress.dom.wrap() // $ExpectError
Cypress.dom.query(el, 'foo') // $ExpectError
Cypress.dom.unwrap() // $ExpectError
Cypress.dom.isDom() // $ExpectError
Cypress.dom.isType(el) // $ExpectError
Cypress.dom.isVisible('') // $ExpectError
Cypress.dom.isHidden('') // $ExpectError
Cypress.dom.isFocusable('') // $ExpectError
Cypress.dom.isTextLike('') // $ExpectError
Cypress.dom.isScrollable('') // $ExpectError
Cypress.dom.isFocused('') // $ExpectError
Cypress.dom.isDetached('') // $ExpectError
Cypress.dom.isAttached('') // $ExpectError
Cypress.dom.isSelector('', 'foo') // $ExpectError
Cypress.dom.isDescendent('', '') // $ExpectError
Cypress.dom.isElement() // $ExpectError
Cypress.dom.isDocument() // $ExpectError
Cypress.dom.isWindow() // $ExpectError
Cypress.dom.isJquery() // $ExpectError
Cypress.dom.isInputType('', 'number') // $ExpectError
Cypress.dom.stringify('', 'foo') // $ExpectError
Cypress.dom.getElements(el) // $ExpectError
Cypress.dom.getContainsSelector(el, 'bar') // $ExpectError
Cypress.dom.getContainsSelector('foo', 'bar', { invalid: false }) // $ExpectError
Cypress.dom.getFirstDeepestElement(el, 1) // $ExpectError
Cypress.dom.getWindowByElement('') // $ExpectError
Cypress.dom.getReasonIsHidden('') // $ExpectError
Cypress.dom.getFirstScrollableParent('') // $ExpectError
Cypress.dom.getFirstFixedOrStickyPositionParent('') // $ExpectError
Cypress.dom.getFirstStickyPositionParent('') // $ExpectError
Cypress.dom.getCoordsByPosition(1) // $ExpectError
Cypress.dom.getElementPositioning('') // $ExpectError
Cypress.dom.getElementAtPointFromViewport(el, 1, 2) // $ExpectError
Cypress.dom.getElementCoordinatesByPosition(doc, 'top') // $ExpectError
Cypress.dom.getElementCoordinatesByPositionRelativeToXY(doc, 1, 2) // $ExpectError
}
namespace CypressTestConfigOverridesTests {
// set config on a per-test basis
it('test', {
animationDistanceThreshold: 10,
defaultCommandTimeout: 6000,
env: {},
execTimeout: 6000,
includeShadowDom: true,
requestTimeout: 6000,
responseTimeout: 6000,
scrollBehavior: 'center',
taskTimeout: 6000,
viewportHeight: 200,
viewportWidth: 200,
waitForAnimations: false
}, () => { })
it('test', {
browser: { name: 'firefox' }
}, () => { })
it('test', {
browser: [{ name: 'firefox' }, { name: 'chrome' }]
}, () => { })
it('test', {
browser: 'firefox',
keystrokeDelay: 0
}, () => { })
it('test', {
browser: { foo: 'bar' }, // $ExpectError
}, () => { })
it('test', {
retries: null,
keystrokeDelay: 0
}, () => { })
it('test', {
retries: 3,
keystrokeDelay: false, // $ExpectError
}, () => { })
it('test', {
retries: {
runMode: 3,
openMode: null
}
}, () => { })
it('test', {
retries: {
runMode: 3,
}
}, () => { })
it('test', {
retries: { run: 3 } // $ExpectError
}, () => { })
it('test', {
testIsolation: false, // $ExpectError
}, () => { })
it.skip('test', {}, () => { })
it.only('test', {}, () => { })
xit('test', {}, () => { })
specify('test', {}, () => { })
specify.only('test', {}, () => { })
specify.skip('test', {}, () => { })
xspecify('test', {}, () => { })
// set config on a per-suite basis
describe('suite', {
browser: { family: 'firefox' },
keystrokeDelay: 0
}, () => { })
describe('suite', {
testIsolation: false,
}, () => { })
context('suite', {}, () => { })
describe('suite', {
browser: { family: 'firefox' },
keystrokeDelay: false // $ExpectError
foo: 'foo' // $ExpectError
}, () => { })
describe.only('suite', {}, () => { })
describe.skip('suite', {}, () => { })
xdescribe('suite', {}, () => { })
}
namespace CypressShadowTests {
cy
.get('.foo')
.shadow()
.find('.bar')
.click()
cy.get('.foo', { includeShadowDom: true }).click()
cy
.get('.foo')
.find('.bar', { includeShadowDom: true })
}
namespace CypressTaskTests {
cy.task<number>('foo') // $ExpectType Chainable<number>
cy.task<number>('foo').then((val) => {
val // $ExpectType number
})
cy.task('foo') // $ExpectType Chainable<unknown>
cy.task('foo').then((val) => {
val // $ExpectType unknown
})
}
namespace CypressSessionsTests {
cy.session('user', () => { })
cy.session({ name: 'bob' }, () => { })
cy.session('user', () => { }, {})
cy.session('user', () => { }, {
validate: () => { }
})
cy.session() // $ExpectError
cy.session('user') // $ExpectError
cy.session(null) // $ExpectError
cy.session('user', () => { }, {
validate: { foo: true } // $ExpectError
})
}
namespace CypressCurrentTest {
Cypress.currentTest.title // $ExpectType string
Cypress.currentTest.titlePath // $ExpectType string[]
Cypress.currentTest() // $ExpectError
}
namespace CypressKeyboardTests {
Cypress.Keyboard.defaults({
keystrokeDelay: 0
})
Cypress.Keyboard.defaults({
keystrokeDelay: 500
})
Cypress.Keyboard.defaults({
keystrokeDelay: false // $ExpectError
})
Cypress.Keyboard.defaults({
delay: 500 // $ExpectError
})
}
namespace CypressOriginTests {
cy.origin('example.com', () => { })
cy.origin('example.com', { args: {} }, (value: object) => { })
cy.origin('example.com', { args: { one: 1, key: 'value', bool: true } }, (value: { one: number, key: string, bool: boolean }) => { })
cy.origin('example.com', { args: [1, 'value', true] }, (value: Array<(number | string | boolean)>) => { })
cy.origin('example.com', { args: 'value' }, (value: string) => { })
cy.origin('example.com', { args: 1 }, (value: number) => { })
cy.origin('example.com', { args: true }, (value: boolean) => { })
cy.origin() // $ExpectError
cy.origin('example.com') // $ExpectError
cy.origin(true) // $ExpectError
cy.origin('example.com', {}) // $ExpectError
cy.origin('example.com', {}, {}) // $ExpectError
cy.origin('example.com', { args: ['value'] }, (value: boolean[]) => { }) // $ExpectError
cy.origin('example.com', {}, (value: undefined) => { }) // $ExpectError
}
namespace CypressGetCookiesTests {
cy.getCookies().then((cookies) => {
cookies // $ExpectType Cookie[]
})
cy.getCookies({ log: true })
cy.getCookies({ timeout: 10 })
cy.getCookies({ domain: 'localhost' })
cy.getCookies({ log: true, timeout: 10, domain: 'localhost' })
cy.getCookies({ log: 'true' }) // $ExpectError
cy.getCookies({ timeout: '10' }) // $ExpectError
cy.getCookies({ domain: false }) // $ExpectError
}
namespace CypressGetAllCookiesTests {
cy.getAllCookies().then((cookies) => {
cookies // $ExpectType Cookie[]
})
cy.getAllCookies({ log: true })
cy.getAllCookies({ timeout: 10 })
cy.getAllCookies({ log: true, timeout: 10 })
cy.getAllCookies({ log: 'true' }) // $ExpectError
cy.getAllCookies({ timeout: '10' }) // $ExpectError
cy.getAllCookies({ other: true }) // $ExpectError
}
namespace CypressGetCookieTests {
cy.getCookie('name').then((cookie) => {
cookie // $ExpectType Cookie | null
})
cy.getCookie('name', { log: true })
cy.getCookie('name', { timeout: 10 })
cy.getCookie('name', { domain: 'localhost' })
cy.getCookie('name', { log: true, timeout: 10, domain: 'localhost' })
cy.getCookie('name', { log: 'true' }) // $ExpectError
cy.getCookie('name', { timeout: '10' }) // $ExpectError
cy.getCookie('name', { domain: false }) // $ExpectError
}
namespace CypressSetCookieTests {
cy.setCookie('name', 'value').then((cookie) => {
cookie // $ExpectType Cookie
})
cy.setCookie('name', 'value', { log: true })
cy.setCookie('name', 'value', { timeout: 10 })
cy.setCookie('name', 'value', {
domain: 'localhost',
path: '/',
secure: true,
httpOnly: false,
expiry: 12345,
sameSite: 'lax',
})
cy.setCookie('name', 'value', {
domain: 'www.foobar.com',
path: '/',
secure: false,
httpOnly: false,
hostOnly: true,
sameSite: 'lax',
})
cy.setCookie('name', 'value', { log: true, timeout: 10, domain: 'localhost' })
cy.setCookie('name') // $ExpectError
cy.setCookie('name', 'value', { log: 'true' }) // $ExpectError
cy.setCookie('name', 'value', { timeout: '10' }) // $ExpectError
cy.setCookie('name', 'value', { domain: false }) // $ExpectError
cy.setCookie('name', 'value', { foo: 'bar' }) // $ExpectError
}
namespace CypressClearCookieTests {
cy.clearCookie('name').then((result) => {
result // $ExpectType null
})
cy.clearCookie('name', { log: true })
cy.clearCookie('name', { timeout: 10 })
cy.clearCookie('name', { domain: 'localhost' })
cy.clearCookie('name', { log: true, timeout: 10, domain: 'localhost' })
cy.clearCookie('name', { log: 'true' }) // $ExpectError
cy.clearCookie('name', { timeout: '10' }) // $ExpectError
cy.clearCookie('name', { domain: false }) // $ExpectError
}
namespace CypressClearCookiesTests {
cy.clearCookies().then((result) => {
result // $ExpectType null
})
cy.clearCookies({ log: true })
cy.clearCookies({ timeout: 10 })
cy.clearCookies({ domain: 'localhost' })
cy.clearCookies({ log: true, timeout: 10, domain: 'localhost' })
cy.clearCookies({ log: 'true' }) // $ExpectError
cy.clearCookies({ timeout: '10' }) // $ExpectError
cy.clearCookies({ domain: false }) // $ExpectError
}
namespace CypressClearAllCookiesTests {
cy.clearAllCookies().then((cookies) => {
cookies // $ExpectType null
})
cy.clearAllCookies({ log: true })
cy.clearAllCookies({ timeout: 10 })
cy.clearAllCookies({ log: true, timeout: 10 })
cy.clearAllCookies({ log: 'true' }) // $ExpectError
cy.clearAllCookies({ timeout: '10' }) // $ExpectError
cy.clearAllCookies({ other: true }) // $ExpectError
}
namespace CypressLocalStorageTests {
cy.getAllLocalStorage().then((result) => {
result // $ExpectType StorageByOrigin
})
cy.getAllLocalStorage({ log: false })
cy.getAllLocalStorage({ log: 'true' }) // $ExpectError
cy.clearAllLocalStorage().then((result) => {
result // $ExpectType null
})
cy.clearAllLocalStorage({ log: false })
cy.clearAllLocalStorage({ log: 'true' }) // $ExpectError
cy.getAllSessionStorage().then((result) => {
result // $ExpectType StorageByOrigin
})
cy.getAllSessionStorage({ log: false })
cy.getAllSessionStorage({ log: 'true' }) // $ExpectError
cy.clearAllSessionStorage().then((result) => {
result // $ExpectType null
})
cy.clearAllSessionStorage({ log: false })
cy.clearAllSessionStorage({ log: 'true' }) // $ExpectError
}
namespace CypressRetriesSpec {
Cypress.config('retries', {
openMode: 0,
runMode: 1
})
Cypress.config('retries', {
openMode: false,
runMode: false,
experimentalStrategy: "detect-flake-and-pass-on-threshold",
experimentalOptions: {
maxRetries: 2,
passesRequired: 2
}
})
Cypress.config('retries', {
openMode: false,
runMode: false,
experimentalStrategy: "detect-flake-but-always-fail",
experimentalOptions: {
maxRetries: 2,
stopIfAnyPassed: true
}
})
Cypress.config('retries', { openMode: false, runMode: true, experimentalStrategy: "detect-flake-and-pass-on-threshold", experimentalOptions: { maxRetries: 2 } }) // $ExpectError
Cypress.config('retries', { openMode: false, runMode: true, experimentalStrategy: "detect-flake-but-always-fail", experimentalOptions: { maxRetries: 2 } }) // $ExpectError
Cypress.config('retries', { openMode: false, runMode: true, experimentalStrategy: "detect-flake-and-pass-on-threshold", experimentalOptions: { passesRequired: 2 } }) // $ExpectError
Cypress.config('retries', { openMode: false, runMode: true, experimentalStrategy: "detect-flake-but-always-fail", experimentalOptions: { stopIfAnyPassed: true } }) // $ExpectError
}
namespace CypressTraversalTests {
cy.wrap({}).prevUntil('a') // $ExpectType Chainable<JQuery<HTMLAnchorElement>>
cy.wrap({}).prevUntil('#myItem') // $ExpectType Chainable<JQuery<HTMLElement>>
cy.wrap({}).prevUntil('span', 'a') // $ExpectType Chainable<JQuery<HTMLSpanElement>>
cy.wrap({}).prevUntil('#myItem', 'a') // $ExpectType Chainable<JQuery<HTMLElement>>
cy.wrap({}).prevUntil('div', 'a', { log: false, timeout: 100 }) // $ExpectType Chainable<JQuery<HTMLDivElement>>
cy.wrap({}).prevUntil('#myItem', 'a', { log: false, timeout: 100 }) // $ExpectType Chainable<JQuery<HTMLElement>>
cy.wrap({}).prevUntil('#myItem', 'a', { log: 'true' }) // $ExpectError
cy.wrap({}).nextUntil('a') // $ExpectType Chainable<JQuery<HTMLAnchorElement>>
cy.wrap({}).nextUntil('#myItem') // $ExpectType Chainable<JQuery<HTMLElement>>
cy.wrap({}).nextUntil('span', 'a') // $ExpectType Chainable<JQuery<HTMLSpanElement>>
cy.wrap({}).nextUntil('#myItem', 'a') // $ExpectType Chainable<JQuery<HTMLElement>>
cy.wrap({}).nextUntil('div', 'a', { log: false, timeout: 100 }) // $ExpectType Chainable<JQuery<HTMLDivElement>>
cy.wrap({}).nextUntil('#myItem', 'a', { log: false, timeout: 100 }) // $ExpectType Chainable<JQuery<HTMLElement>>
cy.wrap({}).nextUntil('#myItem', 'a', { log: 'true' }) // $ExpectError
cy.wrap({}).parentsUntil('a') // $ExpectType Chainable<JQuery<HTMLAnchorElement>>
cy.wrap({}).parentsUntil('#myItem') // $ExpectType Chainable<JQuery<HTMLElement>>
cy.wrap({}).parentsUntil('span', 'a') // $ExpectType Chainable<JQuery<HTMLSpanElement>>
cy.wrap({}).parentsUntil('#myItem', 'a') // $ExpectType Chainable<JQuery<HTMLElement>>
cy.wrap({}).parentsUntil('div', 'a', { log: false, timeout: 100 }) // $ExpectType Chainable<JQuery<HTMLDivElement>>
cy.wrap({}).parentsUntil('#myItem', 'a', { log: false, timeout: 100 }) // $ExpectType Chainable<JQuery<HTMLElement>>
cy.wrap({}).parentsUntil('#myItem', 'a', { log: 'true' }) // $ExpectError
}
namespace CypressRequireTests {
Cypress.require('lodash')
const anydep = Cypress.require('anydep')
anydep // $ExpectType any
const sinon = Cypress.require<sinon.SinonStatic>('sinon') as typeof import('sinon')
sinon // $ExpectType SinonStatic
const lodash = Cypress.require<_.LoDashStatic>('lodash')
lodash // $ExpectType LoDashStatic
Cypress.require() // $ExpectError
Cypress.require({}) // $ExpectError
Cypress.require(123) // $ExpectError
}
namespace CypressGlobalsTests {
Cypress
cy
expect
assert
window.Cypress
window.cy
window.expect
window.assert
globalThis.Cypress
globalThis.cy
globalThis.expect
globalThis.assert
}
| cypress/cli/types/tests/cypress-tests.ts/0 | {
"file_path": "cypress/cli/types/tests/cypress-tests.ts",
"repo_id": "cypress",
"token_count": 14973
} | 17 |
# npm
This directory contains packages that are both used internally inside the Cypress monorepo [`packages`](../packages) and also published independently on npm under the Cypress organization using the `@cypress` prefix. For example, `vite-dev-server` is published as `@cypress/vite-dev-server`.
These are automatically released based on [Semantic Version](https://semver.org) commit message prefixes (`feat`, `chore` etc). A package is automatically released when changes are merged into `develop`. You can read more about this process in [`CONTRIBUTING`](../CONTRIBUTING.md#committing-code).
| cypress/npm/README.md/0 | {
"file_path": "cypress/npm/README.md",
"repo_id": "cypress",
"token_count": 154
} | 18 |
module.exports = {
...require('../../.releaserc'),
}
| cypress/npm/cypress-schematic/.releaserc.js/0 | {
"file_path": "cypress/npm/cypress-schematic/.releaserc.js",
"repo_id": "cypress",
"token_count": 22
} | 19 |
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "cypress-schematics-generate-spec",
"title": "Cypress Generate Spec Options Schema",
"type": "object",
"properties": {
"filename": {
"type": "string",
"description": "Allows users to specify a custom filename.",
"visible": false
},
"path": {
"type": "string",
"format": "path",
"description": "The path where the spec will be created.",
"visible": false
},
"project": {
"type": "string",
"description": "The name of the project to create the spec in.",
"alias": "p",
"$default": {
"$source": "projectName"
}
},
"name": {
"type": "string",
"description": "The name of the spec.",
"alias": "n",
"$default": {
"$source": "argv",
"index": 0
},
"x-prompt": "What should the spec be named?"
},
"component": {
"type": "boolean",
"alias": "c",
"default": false,
"description": "When true, the spec created will be a component spec."
}
},
"required": [
"name"
]
} | cypress/npm/cypress-schematic/src/schematics/ng-generate/cypress-test/schema.json/0 | {
"file_path": "cypress/npm/cypress-schematic/src/schematics/ng-generate/cypress-test/schema.json",
"repo_id": "cypress",
"token_count": 490
} | 20 |
const fs = require('fs')
const path = require('path')
module.exports =
// eslint-disable-next-line no-restricted-syntax
Object.assign({}, ...fs.readdirSync(__dirname)
.filter((filename) => filename.endsWith('.js') && filename !== 'index.js')
.map((filename) => ({ [filename.replace(/\.js$/u, '')]: require(path.resolve(__dirname, filename)) })))
| cypress/npm/eslint-plugin-dev/lib/custom-rules/index.js/0 | {
"file_path": "cypress/npm/eslint-plugin-dev/lib/custom-rules/index.js",
"repo_id": "cypress",
"token_count": 124
} | 21 |
describe('outer', ()=>{
describe('some test', ()=>{
context('some test', ()=>{
it('some test', ()=>{
expect('foo').to.eq('bar')
})
return someFn()
})
})
})
| cypress/npm/eslint-plugin-dev/test/fixtures/no-return-before-pass.js/0 | {
"file_path": "cypress/npm/eslint-plugin-dev/test/fixtures/no-return-before-pass.js",
"repo_id": "cypress",
"token_count": 91
} | 22 |
// @ts-check
/// <reference types="cypress" />
describe('tests that use config object', () => {
it('still works @config', { baseUrl: 'http://localhost:8000' }, () => {
expect(Cypress.config('baseUrl')).to.equal('http://localhost:8000')
})
})
| cypress/npm/grep/cypress/e2e/config-spec.js/0 | {
"file_path": "cypress/npm/grep/cypress/e2e/config-spec.js",
"repo_id": "cypress",
"token_count": 84
} | 23 |
/// <reference types="cypress" />
import {
parseGrep,
parseTitleGrep,
parseFullTitleGrep,
parseTagsGrep,
shouldTestRun,
shouldTestRunTags,
shouldTestRunTitle,
} from '../../src/utils'
describe('utils', () => {
context('parseTitleGrep', () => {
it('grabs the positive title', () => {
const parsed = parseTitleGrep('hello w')
expect(parsed).to.deep.equal({
title: 'hello w',
invert: false,
})
})
it('trims the string', () => {
const parsed = parseTitleGrep(' hello w ')
expect(parsed).to.deep.equal({
title: 'hello w',
invert: false,
})
})
it('inverts the string', () => {
const parsed = parseTitleGrep('-hello w')
expect(parsed).to.deep.equal({
title: 'hello w',
invert: true,
})
})
it('trims the inverted the string', () => {
const parsed = parseTitleGrep(' -hello w ')
expect(parsed).to.deep.equal({
title: 'hello w',
invert: true,
})
})
it('returns null for undefined input', () => {
const parsed = parseTitleGrep()
expect(parsed).to.equal(null)
})
})
context('parseFullTitleGrep', () => {
it('returns list of title greps', () => {
const parsed = parseFullTitleGrep('hello; one; -two')
expect(parsed).to.deep.equal([
{ title: 'hello', invert: false },
{ title: 'one', invert: false },
{ title: 'two', invert: true },
])
})
})
context('parseTagsGrep', () => {
it('parses AND tags', () => {
// run only the tests with all 3 tags
const parsed = parseTagsGrep('@tag1+@tag2+@tag3')
expect(parsed).to.deep.equal([
// single OR part
[
// with 3 AND parts
{ tag: '@tag1', invert: false },
{ tag: '@tag2', invert: false },
{ tag: '@tag3', invert: false },
],
])
})
it('handles dashes in the tag', () => {
const parsed = parseTagsGrep('@smoke+@screen-b')
expect(parsed).to.deep.equal([
[
{ tag: '@smoke', invert: false },
{ tag: '@screen-b', invert: false },
],
])
})
it('parses OR tags spaces', () => {
// run tests with tag1 OR tag2 or tag3
const parsed = parseTagsGrep('@tag1 @tag2 @tag3')
expect(parsed).to.deep.equal([
[{ tag: '@tag1', invert: false }],
[{ tag: '@tag2', invert: false }],
[{ tag: '@tag3', invert: false }],
])
})
it('parses OR tags commas', () => {
// run tests with tag1 OR tag2 or tag3
const parsed = parseTagsGrep('@tag1,@tag2,@tag3')
expect(parsed).to.deep.equal([
[{ tag: '@tag1', invert: false }],
[{ tag: '@tag2', invert: false }],
[{ tag: '@tag3', invert: false }],
])
})
it('parses inverted tag', () => {
const parsed = parseTagsGrep('-@tag1')
expect(parsed).to.deep.equal([[{ tag: '@tag1', invert: true }]])
})
it('parses tag1 but not tag2 with space', () => {
const parsed = parseTagsGrep('@tag1 -@tag2')
expect(parsed).to.deep.equal([
[{ tag: '@tag1', invert: false }],
[{ tag: '@tag2', invert: true }],
])
})
it('forgives extra spaces', () => {
const parsed = parseTagsGrep(' @tag1 -@tag2 ')
expect(parsed).to.deep.equal([
[{ tag: '@tag1', invert: false }],
[{ tag: '@tag2', invert: true }],
])
})
it('parses tag1 but not tag2 with comma', () => {
const parsed = parseTagsGrep('@tag1,-@tag2')
expect(parsed).to.deep.equal([
[{ tag: '@tag1', invert: false }],
[{ tag: '@tag2', invert: true }],
])
})
it('filters out empty tags', () => {
const parsed = parseTagsGrep(',, @tag1,-@tag2,, ,, ,')
expect(parsed).to.deep.equal([
[{ tag: '@tag1', invert: false }],
[{ tag: '@tag2', invert: true }],
])
})
// TODO: would need to change the tokenizer
it.skip('parses tag1 but not tag2', () => {
const parsed = parseTagsGrep('@tag1-@tag2')
expect(parsed).to.deep.equal([
[
{ tag: '@tag1', invert: false },
{ tag: '@tag2', invert: true },
],
])
})
it('allows all tags to be inverted', () => {
const parsed = parseTagsGrep('--@tag1,--@tag2')
expect(parsed).to.deep.equal([
[{ tag: '@tag1', invert: true }, { tag: '@tag2', invert: true }],
])
})
})
context('parseGrep', () => {
// no need to exhaustively test the parsing
// since we want to confirm it works via test names
// and not through the implementation details of
// the parsed object
it('creates just the title grep', () => {
const parsed = parseGrep('hello w')
expect(parsed).to.deep.equal({
title: [
{
title: 'hello w',
invert: false,
},
],
tags: [],
})
})
it('creates object from the grep string only', () => {
const parsed = parseGrep('hello w')
expect(parsed).to.deep.equal({
title: [
{
title: 'hello w',
invert: false,
},
],
tags: [],
})
// check how the parsed grep works against specific tests
expect(shouldTestRun(parsed, 'hello w')).to.equal(true)
expect(shouldTestRun(parsed, 'hello no')).to.equal(false)
})
it('matches one of the titles', () => {
// also should trim each title
const parsed = parseGrep(' hello w; work 2 ')
expect(parsed).to.deep.equal({
title: [
{
title: 'hello w',
invert: false,
},
{
title: 'work 2',
invert: false,
},
],
tags: [],
})
// check how the parsed grep works against specific tests
expect(shouldTestRun(parsed, 'hello w')).to.equal(true)
expect(shouldTestRun(parsed, 'this work 2 works')).to.equal(true)
expect(shouldTestRun(parsed, 'hello no')).to.equal(false)
})
it('creates object from the grep string and tags', () => {
const parsed = parseGrep('hello w', '@tag1+@tag2+@tag3')
expect(parsed).to.deep.equal({
title: [
{
title: 'hello w',
invert: false,
},
],
tags: [
// single OR part
[
// with 3 AND parts
{ tag: '@tag1', invert: false },
{ tag: '@tag2', invert: false },
{ tag: '@tag3', invert: false },
],
],
})
// check how the parsed grep works against specific tests
expect(shouldTestRun(parsed, 'hello w'), 'needs tags').to.equal(false)
expect(shouldTestRun(parsed, 'hello no')).to.equal(false)
// not every tag is present
expect(shouldTestRun(parsed, ['@tag1', '@tag2'])).to.equal(false)
expect(shouldTestRun(parsed, ['@tag1', '@tag2', '@tag3'])).to.equal(true)
expect(
shouldTestRun(parsed, ['@tag1', '@tag2', '@tag3', '@tag4']),
).to.equal(true)
// title matches, but tags do not
expect(shouldTestRun(parsed, 'hello w', ['@tag1', '@tag2'])).to.equal(
false,
)
// tags and title match
expect(
shouldTestRun(parsed, 'hello w', ['@tag1', '@tag2', '@tag3']),
).to.equal(true)
})
})
context('shouldTestRunTags', () => {
// when the user types "used" string
// and the test has the given tags, make sure
// our parsing and decision logic computes the expected result
const shouldIt = (used, tags, expected) => {
const parsedTags = parseTagsGrep(used)
expect(
shouldTestRunTags(parsedTags, tags),
`"${used}" against "${tags}"`,
).to.equal(expected)
}
it('handles AND tags', () => {
shouldIt('smoke+slow', ['fast', 'smoke'], false)
shouldIt('smoke+slow', ['mobile', 'smoke', 'slow'], true)
shouldIt('smoke+slow', ['slow', 'extra', 'smoke'], true)
shouldIt('smoke+slow', ['smoke'], false)
})
it('handles OR tags', () => {
// smoke OR slow
shouldIt('smoke slow', ['fast', 'smoke'], true)
shouldIt('smoke', ['mobile', 'smoke', 'slow'], true)
shouldIt('slow', ['slow', 'extra', 'smoke'], true)
shouldIt('smoke', ['smoke'], true)
shouldIt('smoke', ['slow'], false)
})
it('handles invert tag', () => {
// should not run - we are excluding the "slow"
shouldIt('smoke+-slow', ['smoke', 'slow'], false)
shouldIt('mobile+-slow', ['smoke', 'slow'], false)
shouldIt('smoke -slow', ['smoke', 'fast'], true)
shouldIt('-slow', ['smoke', 'slow'], false)
shouldIt('-slow', ['smoke'], true)
// no tags in the test
shouldIt('-slow', [], true)
})
})
context('shouldTestRun', () => {
// a little utility function to parse the given grep string
// and apply the first argument in shouldTestRun
const checkName = (grep, grepTags) => {
const parsed = parseGrep(grep, grepTags)
expect(parsed).to.be.an('object')
return (testName, testTags = []) => {
expect(testName, 'test title').to.be.a('string')
expect(testTags, 'test tags').to.be.an('array')
return shouldTestRun(parsed, testName, testTags)
}
}
it('simple tag', () => {
const parsed = parseGrep('@tag1')
expect(shouldTestRun(parsed, 'no tag1 here')).to.be.false
expect(shouldTestRun(parsed, 'has @tag1 in the name')).to.be.true
})
it('with invert title', () => {
const t = checkName('-hello')
expect(t('no greetings')).to.be.true
expect(t('has hello world')).to.be.false
})
it('with invert option', () => {
const t = checkName(null, '-@tag1')
expect(t('no tags here')).to.be.true
expect(t('has tag1', ['@tag1'])).to.be.false
expect(t('has other tags', ['@tag2'])).to.be.true
})
it('with AND option', () => {
const t = checkName('', '@tag1+@tag2')
expect(t('no tag1 here')).to.be.false
expect(t('has only @tag1', ['@tag1'])).to.be.false
expect(t('has only @tag2', ['@tag2'])).to.be.false
expect(t('has both tags', ['@tag1', '@tag2'])).to.be.true
})
it('with OR option', () => {
const t = checkName(null, '@tag1 @tag2')
expect(t('no tag1 here')).to.be.false
expect(t('has only @tag1 in the name', ['@tag1'])).to.be.true
expect(t('has only @tag2 in the name', ['@tag2'])).to.be.true
expect(t('has @tag1 and @tag2 in the name', ['@tag1', '@tag2'])).to.be
.true
})
it('OR with AND option', () => {
const t = checkName(null, '@tag1 @tag2+@tag3')
expect(t('no tag1 here')).to.be.false
expect(t('has only @tag1 in the name', ['@tag1'])).to.be.true
expect(t('has only @tag2 in the name', ['@tag2'])).to.be.false
expect(t('has only @tag2 in the name and also @tag3', ['@tag2', '@tag3']))
.to.be.true
expect(
t('has @tag1 and @tag2 and @tag3 in the name', [
'@tag1',
'@tag2',
'@tag3',
]),
).to.be.true
})
it('Multiple invert strings and a simple one', () => {
const t = checkName('-name;-hey;number')
expect(t('number should only be matches without a n-a-m-e')).to.be.true
expect(t('number can\'t be name')).to.be.false
expect(t('The man needs a name')).to.be.false
expect(t('number hey name')).to.be.false
expect(t('numbers hey name')).to.be.false
expect(t('number hsey nsame')).to.be.true
expect(t('This wont match')).to.be.false
})
it('Only inverted strings', () => {
const t = checkName('-name;-hey')
expect(t('I\'m matched')).to.be.true
expect(t('hey! I\'m not')).to.be.false
expect(t('My name is weird')).to.be.false
})
})
context('parseFullTitleGrep', () => {
const shouldIt = (search, testName, expected) => {
const parsed = parseFullTitleGrep(search)
expect(
shouldTestRunTitle(parsed, testName),
`"${search}" against title "${testName}"`,
).to.equal(expected)
}
it('passes for substring', () => {
shouldIt('hello w', 'hello world', true)
shouldIt('-hello w', 'hello world', false)
})
})
})
describe('plugin', () => {
context('excludeSpecPattern', () => {
it('supports an array value', () => {
cy.task('grep', {
excludeSpecPattern: ['**/test2.spec.js', '**/test3.spec.js'],
specPattern: '**/*.spec.js',
env: {
grepTags: 'smoke',
grepFilterSpecs: true,
},
}).then((config) => {
expect(config.specPattern.length).to.equal(1)
expect(config.specPattern[0]).to.contain('test1.spec.js')
})
})
it('supports a string value', () => {
cy.task('grep', {
excludeSpecPattern: '**/test2.spec.js',
specPattern: '**/*.spec.js',
env: {
grepTags: 'smoke',
grepFilterSpecs: true,
},
}).then((config) => {
expect(config.specPattern.length).to.equal(2)
expect(config.specPattern[0]).to.contain('test1.spec.js')
expect(config.specPattern[1]).to.contain('test3.spec.js')
})
})
})
})
| cypress/npm/grep/cypress/e2e/unit.js/0 | {
"file_path": "cypress/npm/grep/cypress/e2e/unit.js",
"repo_id": "cypress",
"token_count": 6160
} | 24 |
{
"hello world: burning 1 of 3": "passed",
"hello world: burning 2 of 3": "passed",
"hello world: burning 3 of 3": "passed",
"works": "pending",
"works 2 @tag1": "pending",
"works 2 @tag1 @tag2": "pending",
"works @tag2": "pending"
}
| cypress/npm/grep/expects/hello-burn.json/0 | {
"file_path": "cypress/npm/grep/expects/hello-burn.json",
"repo_id": "cypress",
"token_count": 99
} | 25 |
{
"hello world": "pending",
"works": "pending",
"works 2 @tag1": "pending",
"works 2 @tag1 @tag2": "passed",
"works @tag2": "pending"
}
| cypress/npm/grep/expects/tag1-and-tag2.json/0 | {
"file_path": "cypress/npm/grep/expects/tag1-and-tag2.json",
"repo_id": "cypress",
"token_count": 64
} | 26 |
# @cypress/puppeteer [beta]
Utilize [Puppeteer's browser API](https://pptr.dev/api) within Cypress with a single command.
> This plugin is in public beta, so we'd love to get your feedback to improve it. Please leave any feedback you have in [this discussion](https://github.com/cypress-io/cypress/discussions/28410).
# Table of Contents
- [Installation](#installation)
- [Compatibility](#compatibility)
- [Usage](#usage)
- [API](#api)
- [Examples](#examples)
- [Contributing](#contributing)
- [Changelog](./CHANGELOG.md)
# Installation
## npm
```sh
npm install --save-dev @cypress/puppeteer
```
## yarn
```sh
yarn add --dev @cypress/puppeteer
```
## With TypeScript
Add the following in `tsconfig.json`:
```json
{
"compilerOptions": {
"types": ["cypress", "@cypress/puppeteer/support"]
}
}
```
## Compatibility
`@cypress/puppeteer` requires Cypress version 13.6.0 or greater.
Only Chromium-based browsers (e.g. Chrome, Chromium, Electron) are supported.
## Usage
`@cypress/puppeteer` is set up in your Cypress config and support file, then executed in your spec. See [API](#api) and [Examples](#examples) below for more details.
While the `cy.puppeteer()` command is executed in the browser, the majority of the Puppeteer execution is run in the Node process via your Cypress config. You pass a string message name to `cy.puppeteer()` that indicates which message handler to execute in the Cypress config. This is similar to how [cy.task()](on.cypress.io/task) operates.
In your Cypress config (e.g. `cypress.config.ts`):
```typescript
import { setup } from '@cypress/puppeteer'
export default defineConfig({
e2e: {
setupNodeEvents (on) {
setup({
on,
onMessage: {
async myMessageHander (browser) {
// Utilize the Puppeteer browser instance and the Puppeteer API to interact with and automate the browser
},
},
})
},
},
}
```
In your support file (e.g. `cypress/support/e2e.ts`):
```typescript
import '@cypress/puppeteer/support'
```
In your spec (e.g. `spec.cy.ts`):
```typescript
it('switches to and tests a new tab', () => {
cy.visit('/')
cy.get('button').click() // opens a new tab
cy
.puppeteer('myMessageHander')
.should('equal', 'You said: Hello from Page 1')
})
```
## API
### Cypress Config - setup
This sets up `@cypress/puppeteer` message handlers that run Puppeteer browser automation.
```typescript
setup(options)
```
#### Options
- `on` _required_: The `on` event registration function provided by `setupNodeEvents`
- `onMessage` _required_: An object with string keys and function values (see more details [below](#onmessage))
- `puppeteer` _optional_: The `puppeteer` library imported from `puppeteer-core`, overriding the default version of `puppeteer-core` used by this plugin
##### onMessage
The keys provided in this are used to invoke their corresponding functions by calling `cy.puppeteer(key)` in your Cypress test.
The functions should contain Puppeteer code for automating the browser. The code is executed within Node.js and not within the browser, so Cypress commands and DOM APIs cannot be utilized.
The functions receive the following arguments:
###### browser
A [puppeteer browser instance](https://pptr.dev/api/puppeteer.browser) connected to the Cypress-launched browser.
###### ...args
The rest of the arguments are any de-serialized arguments passed to the `cy.puppeteer()` command from your Cypress test.
### Cypress Config - retry
This is a utility function provided to aid in retrying actions that may initially fail.
```typescript
retry(functionToRetry[, options])
```
#### functionToRetry
_required_
A function that will run and retry if an error is thrown. If an error is not thrown, `retry` will return the value returned by this function.
The function will continue to run at the default or configured interval until the default or configured timeout, at which point `retry` will throw an error and cease retrying this function.
#### Options
_optional_
- `timeout` _optional_: The total time in milliseconds during which to attempt retrying the function. Default: `4000ms`
- `delayBetweenTries` _optional_: The time to wait between retries. Default: `200ms`
### Cypress Spec - cy.puppeteer()
```typescript
cy.puppeteer(messageName[, ...args])
```
#### messageName
_required_
A string matching one of the keys passed to the `onMessage` option of `setup` in your Cypress config.
#### ...args
_optional_
Values that will be passed to the message handler. These values must be JSON-serializable.
Example:
```typescript
// spec
cy.puppeteer('testNewTab', 'value 1', 42, [true, false])
// Cypress config
setup({
on,
onMessage: {
testNewTab (browser, stringArg, numberArg, arrayOfBooleans) {
// stringArg === 'value 1'
// numberArg === 42
// arrayOfBooleans[0] === true / arrayOfBooleans[1] === false
}
}
})
```
## Examples
These examples can be found and run in the [Cypress tests of this package](./cypress) with this project's [cypress.config.ts](./cypress.config.ts).
While these examples use tabs, they could just as easily apply to windows. Tabs and windows are essentially the same things as far as Puppeteer is concerned and encapsulated by instances of the [Page class](https://pptr.dev/api/puppeteer.page/).
### Switching to a new tab
This example demonstrates the following:
- Switching to a tab opened by an action in the Cypress test
- Getting the page instance via Puppeteer utilizing the `retry` function
- Getting page references and content via puppeteer
- Passing that content back to be asserted on in Cypress
_spec.cy.ts_
```typescript
it('switches to a new tab', () => {
cy.visit('/cypress/fixtures/page-1.html')
cy.get('input').type('Hello from Page 1')
cy.get('button').click() // Triggers a new tab to open
cy
.puppeteer('switchToTabAndGetContent')
.should('equal', 'You said: Hello from Page 1')
})
```
_cypress.config.ts_
```typescript
import { defineConfig } from 'cypress'
import type { Browser as PuppeteerBrowser, Page } from 'puppeteer-core'
import { setup, retry } from '@cypress/puppeteer'
export default defineConfig({
e2e: {
setupNodeEvents (on) {
setup({
on,
onMessage: {
async switchToTabAndGetContent (browser: PuppeteerBrowser) {
// In this message handler, we utilize the Puppeteer API to interact with the browser and the new tab that our Cypress tests has opened
// Utilize the retry since the page may not have opened and loaded by the time this runs
const page = await retry<Promise<Page>>(async () => {
// The browser will (eventually) have 2 tabs open: the Cypress tab and the newly opened tab
// In Puppeteer, tabs and windows are called pages
const pages = await browser.pages()
// Try to find the page we want to interact with
const page = pages.find((page) => page.url().includes('page-2.html'))
// If we can't find the page, it probably hasn't loaded yet, so throw an error to signal that this function should retry
if (!page) throw new Error('Could not find page')
// Otherwise, return the page instance and it will be returned by the `retry` function itself
return page
})
// Cypress will maintain focus on the Cypress tab within the browser. It's generally a good idea to bring the page to the front to interact with it.
await page.bringToFront()
const paragraph = (await page.waitForSelector('p'))!
const paragraphText = await page.evaluate((el) => el.textContent, paragraph)
// Clean up any references before finishing up
paragraph.dispose()
await page.close()
// Return the paragraph text and it will be the value yielded by the `cy.puppeteer()` invocation in the spec
return paragraphText
},
},
})
},
},
})
```
### Creating a new tab
This example demonstrates the following:
- Passing a non-default version of puppeteer to `@cypress/puppeteer`
- Passing arguments from `cy.puppeteer()` to the message handler
- Creating a new tab and visiting a page via Puppeteer
- Getting page references and content via puppeteer
- Passing that content back to be asserted on in Cypress
_spec.cy.ts_
```typescript
it('creates a new tab', () => {
cy.visit('/cypress/fixtures/page-3.html')
// We get a dynamic value from the page and pass it through to the puppeteer
// message handler
cy.get('#message').invoke('text').then((message) => {
cy.puppeteer('createTabAndGetContent', message)
.should('equal', 'I approve this message: Cypress and Puppeteer make a great combo')
})
})
```
_cypress.config.ts_
```typescript
import { defineConfig } from 'cypress'
import puppeteer, { Browser as PuppeteerBrowser, Page } from 'puppeteer-core'
import { setup, retry } from '@cypress/puppeteer'
export default defineConfig({
e2e: {
setupNodeEvents (on) {
setup({
on,
// Pass in your own version of puppeteer to be used instead of the default one
puppeteer,
onMessage: {
async createTabAndGetContent (browser: PuppeteerBrowser, text: string) {
// In this message handler, we utilize the Puppeteer API to interact with the browser, creating a new tab and getting its content
// This will create a new tab within the Cypress-launched browser
const page = await browser.newPage()
// Text comes from the test invocation of `cy.puppeteer()`
await page.goto(`http://localhost:8000/cypress/fixtures/page-4.html?text=${text}`)
const paragraph = (await page.waitForSelector('p'))!
const paragraphText = await page.evaluate((el) => el.textContent, paragraph)
// Clean up any references before finishing up
paragraph.dispose()
await page.close()
// Return the paragraph text and it will be the value yielded by the `cy.puppeteer()` invocation in the spec
return paragraphText
},
},
})
},
},
})
```
## Troubleshooting
### Error: Cannot communicate with the Cypress Chrome extension. Ensure the extension is enabled when using the Puppeteer plugin.
If you receive this error in your command log, the Puppeteer plugin was unable to communicate with the Cypress extension. This extension is necessary in order to re-activate the main Cypress tab after a Puppeteer command, when running in open mode.
* Ensure this extension is enabled in the instance of Chrome that Cypress launches by visiting chrome://extensions/
* Ensure the Cypress extension is allowed by your company's security policy by its extension id, `caljajdfkjjjdehjdoimjkkakekklcck`
## Contributing
Build the TypeScript files:
```shell
yarn build
```
Watch the TypeScript files and rebuild on file change:
```shell
yarn watch
```
Open Cypress tests:
```shell
yarn cypress:open
```
Run Cypress tests once:
```shell
yarn cypress:run
```
Run all unit tests once:
```shell
yarn test
```
Run unit tests in watch mode:
```shell
yarn test-watch
```
## [Changelog](./CHANGELOG.md)
| cypress/npm/puppeteer/README.md/0 | {
"file_path": "cypress/npm/puppeteer/README.md",
"repo_id": "cypress",
"token_count": 3846
} | 27 |
Cypress.Commands.add('puppeteer', (name, ...args) => {
Cypress.log({
name: 'puppeteer',
message: name,
})
cy.task('__cypressPuppeteer__', { name, args }, { log: false }).then((result: any) => {
if (result && result.__error__) {
throw new Error(`cy.puppeteer() failed with the following error:\n> ${result.__error__.message || result.__error__}`)
}
return result
})
})
| cypress/npm/puppeteer/src/support/index.ts/0 | {
"file_path": "cypress/npm/puppeteer/src/support/index.ts",
"repo_id": "cypress",
"token_count": 161
} | 28 |
/// <reference types="cypress" />
import React from 'react'
import { mount } from '@cypress/react'
import { Counter } from './counter.jsx'
/* eslint-env mocha */
describe('Counter with access', () => {
it('works', () => {
mount(<Counter />)
cy.contains('count: 0')
.click()
.contains('count: 1')
.click()
.contains('count: 2')
})
it('allows access via reference', () => {
mount(<Counter />)
// the window.counter was set from the Counter's constructor
cy.window()
.should('have.property', 'counter')
.its('state')
.should('deep.equal', { count: 0 })
// let's change the state of the component
cy.window()
.its('counter')
.invoke('setState', {
count: 101,
})
// the UI should update to reflect the new count
cy.contains('count: 101').should('be.visible')
})
})
| cypress/npm/react/cypress/component/advanced/app-action-example/counter.cy.jsx/0 | {
"file_path": "cypress/npm/react/cypress/component/advanced/app-action-example/counter.cy.jsx",
"repo_id": "cypress",
"token_count": 318
} | 29 |
// example from https://reactjs.org/docs/hooks-overview.html
import React, { useState, useEffect } from 'react'
export default function Counter2WithHooks () {
const [count, setCount] = useState(0)
useEffect(() => {
document.title = `You clicked ${count} times`
})
return (
<div>
<p>You clicked {count} times</p>
<button id="increment" onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
)
}
| cypress/npm/react/cypress/component/advanced/hooks/counter2-with-hooks.jsx/0 | {
"file_path": "cypress/npm/react/cypress/component/advanced/hooks/counter2-with-hooks.jsx",
"repo_id": "cypress",
"token_count": 175
} | 30 |
import React from 'react'
// use named import "get" from the module
import { get } from 'axios'
export class Users extends React.Component {
constructor (props) {
super(props)
this.state = {
users: [],
}
}
componentDidMount () {
get('https://jsonplaceholder.cypress.io/users?_limit=3').then((response) => {
// JSON responses are automatically parsed.
this.setState({
users: response.data,
})
})
}
render () {
return (
<div>
{this.state.users.map((user) => (
<li key={user.id}>
<strong>{user.id}</strong> - {user.name}
</li>
))}
</div>
)
}
}
| cypress/npm/react/cypress/component/advanced/mocking-axios/2-users-named.jsx/0 | {
"file_path": "cypress/npm/react/cypress/component/advanced/mocking-axios/2-users-named.jsx",
"repo_id": "cypress",
"token_count": 303
} | 31 |
# React Router v6
We are testing the navigation in the [app.jsx](app.jsx) when it is surrounded by a React Router from [react-router-dom](https://github.com/ReactTraining/react-router#readme)
- [spec.cy.jsx](spec.cy.jsx) uses `BrowserRouter`
- [in-memory.cy.jsx](in-memory.cy.jsx) uses `MemoryRouter`

| cypress/npm/react/cypress/component/advanced/react-router-v6/README.md/0 | {
"file_path": "cypress/npm/react/cypress/component/advanced/react-router-v6/README.md",
"repo_id": "cypress",
"token_count": 129
} | 32 |
import React from 'react'
import { mount } from '@cypress/react'
// test retries from
// https://github.com/cypress-io/cypress/pull/3968
// you can skip the tests if there is no retries feature
const describeOrSkip = Cypress.getTestRetries ? describe : describe.skip
describeOrSkip('Test', () => {
const Hello = () => {
// this is how you can get the current retry number
// attempt 1: (first test execution) retry = 0
// attempt 2: (second test execution) retry = 1
// attempt 3: retry = 2,
// etc
const n = cy.state('test').currentRetry
? cy.state('test').currentRetry()
: 0
return <div>retry {n}</div>
}
it('does not retry', { retries: 0 }, () => {
mount(<Hello />)
cy.contains('retry 0')
// now let's fail the test - it won't retry it
// enable manually to observe
// cy.contains('retry 1')
})
it('retries', { retries: 3 }, () => {
mount(<Hello />)
// now let's fail the test - it will retry several times and pass
cy.contains('retry 3', { timeout: 1500 })
})
})
| cypress/npm/react/cypress/component/advanced/test-retries/spec.cy.jsx/0 | {
"file_path": "cypress/npm/react/cypress/component/advanced/test-retries/spec.cy.jsx",
"repo_id": "cypress",
"token_count": 383
} | 33 |
body {
font: 14px 'Century Gothic', Futura, sans-serif;
margin: 20px;
}
ol,
ul {
padding-left: 30px;
}
.board-row:after {
clear: both;
content: '';
display: table;
}
.status {
margin-bottom: 10px;
}
.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
line-height: 34px;
height: 34px;
margin-right: -1px;
margin-top: -1px;
padding: 0;
text-align: center;
width: 34px;
}
.square:focus {
outline: none;
}
.kbd-navigation .square:focus {
background: #ddd;
}
.game {
display: flex;
flex-direction: row;
}
.game-info {
margin-left: 20px;
}
| cypress/npm/react/cypress/component/advanced/tutorial/tic-tac-toe.css/0 | {
"file_path": "cypress/npm/react/cypress/component/advanced/tutorial/tic-tac-toe.css",
"repo_id": "cypress",
"token_count": 275
} | 34 |
/// <reference types="cypress" />
import React from 'react'
import { mount } from '@cypress/react'
import styles from './Button.module.css'
import { Button } from './Button.jsx'
describe('Button', () => {
it('renders orange styles', () => {
mount(<Button name="Orange" orange />)
cy.get('div > button')
.parent()
.should('have.class', styles.orange)
.find('button')
.should('have.css', 'background-color', 'rgb(245, 146, 62)')
})
})
| cypress/npm/react/cypress/component/basic/css-modules/css-modules-orange-button.cy.jsx/0 | {
"file_path": "cypress/npm/react/cypress/component/basic/css-modules/css-modules-orange-button.cy.jsx",
"repo_id": "cypress",
"token_count": 167
} | 35 |
import React from 'react'
import { mount } from '@cypress/react'
const Login = () => {
return (
<div>
<div>Login by clicking below</div>
<a href="/foo">click me</a>
</div>
)
}
describe('full navigation', () => {
it('should not happen', () => {
mount(<Login />)
const clicked = cy.stub()
cy.get('a').invoke('on', 'click', (e) => e.preventDefault() || clicked())
cy.get('a').click()
cy.wrap(clicked).should('have.been.calledOnce')
})
})
| cypress/npm/react/cypress/component/basic/full-navigation.cy.jsx/0 | {
"file_path": "cypress/npm/react/cypress/component/basic/full-navigation.cy.jsx",
"repo_id": "cypress",
"token_count": 195
} | 36 |
/// <reference types="cypress" />
import Game, { Board, calculateWinner } from './game.jsx'
import React from 'react'
import { mount } from '@cypress/react'
import './tic-tac-toe.css'
// for now need a constructor, otherwise getting "Weak map" key
const BoardWrap = ({ squares, onClick }) => {
return (
<div className="game">
<div className="game-board">
<Board squares={squares} onClick={onClick} />
</div>
</div>
)
}
beforeEach(() => {
cy.viewport(400, 200)
})
it('renders empty Board', () => {
const squares = Array(9).fill(null)
const onClick = cy.stub()
mount(<BoardWrap squares={squares} onClick={onClick} />)
cy.get('.board-row')
.eq(0)
.find('.square')
.eq(0)
.click()
.then(() => {
expect(onClick).to.have.been.calledWith(0)
})
})
it('renders Board with a few squares filled', () => {
const squares = Array(9).fill(null)
squares[0] = 'X'
squares[1] = 'O'
mount(<BoardWrap squares={squares} />)
cy.get('.board-row')
.eq(0)
.find('.square')
.eq(0)
.should('have.text', 'X')
cy.get('.board-row')
.eq(0)
.find('.square')
.eq(1)
.should('have.text', 'O')
})
it('plays the game', () => {
mount(<Game />)
cy.contains('.game-info', 'Next player: X').should('be.visible')
cy.get('.board-row')
.eq(0)
.find('.square')
.eq(0)
.click()
cy.get('.board-row')
.eq(1)
.find('.square')
.eq(0)
.click()
cy.get('.board-row')
.eq(0)
.find('.square')
.eq(1)
.click()
cy.get('.board-row')
.eq(1)
.find('.square')
.eq(1)
.click()
// X finishes the first row
cy.get('.board-row')
.eq(0)
.find('.square')
.eq(2)
.click()
cy.contains('.game-info', 'Winner: X').should('be.visible')
// history of moves
cy.get('ol li')
.should('have.length', 6)
.first()
.should('have.text', 'Go to game start')
.click()
})
context('calculateWinner', () => {
// we can unit test our winner calculation function!
it('returns null for empty board', () => {
const squares = Array(9).fill(null)
const winner = calculateWinner(squares)
expect(winner).to.be.null
})
it('returns X for first row of X', () => {
const squares = ['X', 'X', 'X']
const winner = calculateWinner(squares)
expect(winner).to.equal('X')
})
it('returns O for second row of O', () => {
// preserve our Tic-Tac-Toe board formatting
// prettier-ignore
const squares = [
'X', 'X', null,
'O', 'O', 'O',
null, null, 'X',
]
const winner = calculateWinner(squares)
expect(winner).to.equal('O')
})
it('returns O for second row of O', () => {
// preserve our Tic-Tac-Toe board formatting
// prettier-ignore
const squares = [
'X', 'X', null,
'O', 'O', 'O',
null, null, 'X',
]
const winner = calculateWinner(squares)
expect(winner).to.equal('O')
})
it('returns X for diagonal', () => {
const _ = null
const O = 'O'
const X = 'X'
// preserve our Tic-Tac-Toe board formatting
// prettier-ignore
const squares = [
_, _, X,
O, X, O,
X, _, O,
]
const winner = calculateWinner(squares)
expect(winner).to.equal(X)
})
})
| cypress/npm/react/cypress/component/basic/react-tutorial/game.cy.jsx/0 | {
"file_path": "cypress/npm/react/cypress/component/basic/react-tutorial/game.cy.jsx",
"repo_id": "cypress",
"token_count": 1332
} | 37 |
/// <reference types="cypress" />
import React, { useLayoutEffect, useEffect } from 'react'
import ReactDom from 'react-dom'
import { mount, getContainerEl } from '@cypress/react'
it('should not run unmount effect cleanup when rerendering', () => {
const layoutEffectCleanup = cy.stub()
const effectCleanup = cy.stub()
const Component = ({ input }) => {
useLayoutEffect(() => {
return layoutEffectCleanup
}, [input])
useEffect(() => {
return effectCleanup
}, [])
return <div>{input}</div>
}
mount(<Component input="0" />).then(({ rerender }) => {
expect(layoutEffectCleanup).to.have.been.callCount(0)
expect(effectCleanup).to.have.been.callCount(0)
rerender(<Component input="0" />).then(() => {
expect(layoutEffectCleanup).to.have.been.callCount(0)
expect(effectCleanup).to.have.been.callCount(0)
})
rerender(<Component input="1" />).then(() => {
expect(layoutEffectCleanup).to.have.been.callCount(1)
expect(effectCleanup).to.have.been.callCount(0)
})
})
})
it('should run unmount effect cleanup when unmounting', () => {
const layoutEffectCleanup = cy.stub()
const effectCleanup = cy.stub()
const Component = ({ input }) => {
useLayoutEffect(() => {
return layoutEffectCleanup
}, [])
useEffect(() => {
return effectCleanup
}, [])
return <div>{input}</div>
}
mount(<Component input="0" />).then(({ rerender }) => {
expect(layoutEffectCleanup).to.have.been.callCount(0)
expect(effectCleanup).to.have.been.callCount(0)
rerender(<Component input="1" />).then(() => {
expect(layoutEffectCleanup).to.have.been.callCount(0)
expect(effectCleanup).to.have.been.callCount(0)
})
cy
.then(() => ReactDom.unmountComponentAtNode(getContainerEl()))
.then(() => {
expect(layoutEffectCleanup).to.have.been.callCount(1)
expect(effectCleanup).to.have.been.callCount(1)
})
})
})
| cypress/npm/react/cypress/component/basic/rerender/effects.cy.jsx/0 | {
"file_path": "cypress/npm/react/cypress/component/basic/rerender/effects.cy.jsx",
"repo_id": "cypress",
"token_count": 749
} | 38 |
/// <reference types="cypress" />
import Comp from './comp.jsx'
import React from 'react'
import { mount, unmount } from '@cypress/react'
it('calls callbacks on mount and unmount', () => {
const onMount = cy.stub()
const onUnmount = cy.stub()
// mount is an async call
mount(<Comp onMount={onMount} onUnmount={onUnmount} />)
cy.then(() => {
expect(onMount).to.have.been.calledOnce
expect(onUnmount).to.have.not.been.called
})
cy.contains('Component with').should('be.visible')
let stub = cy.stub()
try {
unmount()
} catch (e) {
expect(e.message).to.eq('`unmount` is no longer supported.')
stub()
}
expect(stub).to.have.been.calledOnce
})
| cypress/npm/react/cypress/component/basic/unmount/comp.cy.jsx/0 | {
"file_path": "cypress/npm/react/cypress/component/basic/unmount/comp.cy.jsx",
"repo_id": "cypress",
"token_count": 257
} | 39 |
{
"name": "@cypress/react",
"version": "0.0.0-development",
"description": "Test React components using Cypress",
"main": "dist/cypress-react.cjs.js",
"scripts": {
"build": "rimraf dist && rollup -c rollup.config.mjs",
"postbuild": "node ../../scripts/sync-exported-npm-with-cli.js",
"check-ts": "tsc --noEmit",
"cy:open": "node ../../scripts/cypress.js open --component",
"cy:open:debug": "node --inspect-brk ../../scripts/start.js --component-testing --run-project ${PWD}",
"cy:run": "node ../../scripts/cypress.js run --component",
"cy:run:debug": "node --inspect-brk ../../scripts/start.js --component-testing --run-project ${PWD}",
"lint": "eslint --ext .js,.jsx,.ts,.tsx,.json, .",
"test": "yarn cy:run",
"watch": "yarn build --watch --watch.exclude ./dist/**/*"
},
"devDependencies": {
"@cypress/mount-utils": "0.0.0-development",
"@types/semver": "7.5.0",
"@vitejs/plugin-react": "4.0.0",
"axios": "0.21.2",
"cypress": "0.0.0-development",
"prop-types": "15.7.2",
"react": "16.8.6",
"react-dom": "16.8.6",
"react-router": "6.0.0-alpha.1",
"react-router-dom": "6.0.0-alpha.1",
"semver": "^7.5.3",
"typescript": "~5.4.5",
"vite": "4.5.2",
"vite-plugin-require-transform": "1.0.12"
},
"peerDependencies": {
"@types/react": "^16.9.16 || ^17.0.0",
"cypress": "*",
"react": "^=16.x || ^=17.x",
"react-dom": "^=16.x || ^=17.x"
},
"files": [
"dist"
],
"types": "dist/index.d.ts",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/cypress-io/cypress.git"
},
"homepage": "https://github.com/cypress-io/cypress/blob/develop/npm/react/#readme",
"bugs": "https://github.com/cypress-io/cypress/issues/new?assignees=&labels=npm%3A%20%40cypress%2Freact&template=1-bug-report.md&title=",
"keywords": [
"react",
"cypress",
"cypress-io",
"test",
"testing"
],
"contributors": [
{
"name": "Dmitriy Kovalenko",
"social": "@dmtrKovalenko"
},
{
"name": "Brian Mann",
"social": "@brian-mann"
},
{
"name": "Barthélémy Ledoux",
"social": "@elevatebart"
},
{
"name": "Lachlan Miller",
"social": "@lmiller1990"
},
{
"name": "Jessica Sachs",
"social": "@_JessicaSachs"
}
],
"unpkg": "dist/cypress-react.browser.js",
"module": "dist/cypress-react.esm-bundler.js",
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
},
"publishConfig": {
"access": "public"
},
"nx": {
"targets": {
"build": {
"dependsOn": [
"!@cypress/react18:build"
],
"outputs": [
"{workspaceRoot}/cli/react",
"{projectRoot}/dist"
]
}
}
},
"standard": {
"globals": [
"Cypress",
"cy",
"expect"
]
}
}
| cypress/npm/react/package.json/0 | {
"file_path": "cypress/npm/react/package.json",
"repo_id": "cypress",
"token_count": 1422
} | 40 |
import React from 'react'
// @ts-expect-error
import ReactDOM from 'react-dom/client'
import { getContainerEl } from '@cypress/mount-utils'
import {
makeMountFn,
makeUnmountFn,
} from '@cypress/react'
import type {
MountOptions,
MountReturn,
InternalMountOptions,
UnmountArgs,
} from '@cypress/react'
let root: ReactDOM.Root | null
const cleanup = () => {
if (root) {
root.unmount()
root = null
return true
}
return false
}
/**
* Mounts a React component into the DOM.
* @param {import('react').JSX.Element} jsx The React component to mount.
* @param {MountOptions} options Options to pass to the mount function.
* @param {string} rerenderKey A key to use to force a rerender.
*
* @example
* import { mount } from '@cypress/react'
* import { Stepper } from './Stepper'
*
* it('mounts', () => {
* mount(<StepperComponent />)
* cy.get('[data-cy=increment]').click()
* cy.get('[data-cy=counter]').should('have.text', '1')
* }
*
* @see {@link https://on.cypress.io/mounting-react} for more details.
*
* @returns {Cypress.Chainable<MountReturn>} The mounted component.
*/
export function mount (jsx: React.ReactNode, options: MountOptions = {}, rerenderKey?: string) {
// Remove last mounted component if cy.mount is called more than once in a test
// React by default removes the last component when calling render, but we should remove the root
// to wipe away any state
cleanup()
const internalOptions: InternalMountOptions = {
reactDom: ReactDOM,
render: (reactComponent: ReturnType<typeof React.createElement>, el: HTMLElement) => {
if (!root) {
root = ReactDOM.createRoot(el)
}
return root.render(reactComponent)
},
unmount: internalUnmount,
cleanup,
}
return makeMountFn('mount', jsx, { ReactDom: ReactDOM, ...options }, rerenderKey, internalOptions)
}
function internalUnmount (options = { log: true }) {
return makeUnmountFn(options)
}
/**
* Removed as of Cypress 11.0.0.
* @see https://on.cypress.io/migration-11-0-0-component-testing-updates
*/
export function unmount (options: UnmountArgs = { log: true }) {
// @ts-expect-error - undocumented API
Cypress.utils.throwErrByPath('mount.unmount')
}
// Re-export this to help with migrating away from `unmount`
export {
getContainerEl,
}
export type {
MountOptions,
MountReturn,
}
| cypress/npm/react18/src/index.ts/0 | {
"file_path": "cypress/npm/react18/src/index.ts",
"repo_id": "cypress",
"token_count": 800
} | 41 |
version: 2
snapshot:
widths:
- 1280
min-height: 1024
discovery:
network-idle-timeout: 750
| cypress/npm/vite-dev-server/.percy.yml/0 | {
"file_path": "cypress/npm/vite-dev-server/.percy.yml",
"repo_id": "cypress",
"token_count": 40
} | 42 |
import { devServer } from './devServer'
export { devServer }
export default devServer
| cypress/npm/vite-dev-server/src/index.ts/0 | {
"file_path": "cypress/npm/vite-dev-server/src/index.ts",
"repo_id": "cypress",
"token_count": 25
} | 43 |
const __cypressModuleCache = new Map()
const NO_REDEFINE_LIST = new Set(['prototype'])
let debug = false
function createProxyModule (module) {
// What we build our module proxy off of depends on whether the module has a default export
// We need to be able to support `import DefaultValue from 'module'` => `const DefaultValue = __cypressModule(module)`
const base = module.default || module
let target
// Work around for the fact that a module with a default export needs to work the same way via object destructuring
// for this module remapping concept to work
// ```
// import TheDefault from 'module'
// `TheDefault` could be an object or a function
// ```
if (typeof base === 'function') {
target = function (...params) {
if (typeof target.default === 'function') {
return target.default.apply(this, params)
}
if (typeof module === 'function') {
return module.apply(this, params)
}
}
} else {
target = {}
}
const proxies = {}
function redefinePropertyDescriptors (module, overrides) {
Object.entries(Object.getOwnPropertyDescriptors(module)).forEach(([key, descriptor]) => {
if (Array.isArray(module)) {
return
}
if (NO_REDEFINE_LIST.has(key)) {
log(`⏭️ Skipping ${key}`)
return
}
log(`🧪 Redefining ${key}`)
const params = {
...descriptor,
...overrides,
}
// If a property defines accessors it cannot also specify `value` and/or `writable`.
// Those are implicit from the presence of the accessor functions.
if ('get' in params || 'set' in params) {
delete params.writable
delete params.value
}
Object.defineProperty(target, key, params)
// The underlying value could be a raw value *or* a value provided by a getter
const describedValue = descriptor.value || descriptor.get?.()
if (typeof describedValue === 'function') {
// This is how you can see if something is a class
// TODO: Revisit, there has to be a better way to do this
// Important! RegEx instances are stateful, do not extract to a constant
const isClass = /^class\s.+?\{.+?\}/gms.test(describedValue.toString())
if (isClass) {
log(`🏗️ Handling ${key} as a constructor`)
proxies[key] = function (...params) {
// Edge case - use `apply` with `new` to create a class instance
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/construct
return Reflect.construct(target[key], params)
}
} else {
log(`🎁 Handling ${key} with a standard wrapper function`)
proxies[key] = function (...params) {
// Prefer invoking with `apply` so we get proper context in the invoked function
if (target[key].apply) {
return target[key].apply(this, params)
}
// Certain weird edge-cases manage to create functions without the Function
// prototype, thus no `apply` 🤷. Fall back to straight invocation
return target[key](params)
}
}
proxies[key].prototype = target[key].prototype
} else {
log(`${key} is not a function`)
}
})
}
// Do not proxify arrays - you can't spy on an array, no need.
if (Array.isArray(module.default)) {
return module.default
}
if (module.default) {
redefinePropertyDescriptors(module.default, {
writable: true,
enumerable: true,
})
}
redefinePropertyDescriptors(module, {
configurable: true,
writable: true,
})
const moduleProxy = new Proxy(target, {
get (_, prop, receiver) {
const value = target[prop]
if (typeof value === 'function') {
// Check to see if this retrieval is coming from a sinon `spy` creation
// If so, we want to supply the 'true' function rather than our proxied version
// so the spy can call through to the real implementation
const stack = new Error().stack
if (stack?.includes('Sandbox.spy')) {
log(`🕵️ Detected ${prop} is being defined as a Sinon spy`)
return value
}
// Otherwise, return our proxied function implementation
return proxies[prop]
}
return target[prop]
},
set (obj, prop, value) {
target[prop] = value
if (typeof value === 'function' && !(prop in proxies)) {
proxies[prop] = function (...params) {
return target[prop].apply(this, params)
}
}
return true
},
defineProperty (_, key, descriptor) {
// Ignore `define` attempts to set a sinon proxy, but return true anyways
// Allowing define would blow away our function proxy
// Sinon circles back and attempts to set via `set` anyways so this isn't necessary
if (descriptor.value?.isSinonProxy) {
return true
}
Object.defineProperty(target, key, { ...descriptor, writable: true, configurable: true })
return true
},
deleteProperty (_, prop) {
// Don't allow deletion - Sinon tries to delete things as a cleanup activity which breaks our proxied functions
return true
},
})
return moduleProxy
}
function log (msg) {
if (!debug) {
return
}
console.log(`[cypress:vite-plugin-cypress-esm]: ${msg}`)
}
function cacheAndProxifyModule (id, module) {
if (__cypressModuleCache.has(module)) {
return __cypressModuleCache.get(module)
}
log(`🔨 creating proxy module for ${id}`)
try {
const moduleProxy = createProxyModule(module)
log(`✅ created proxy module for ${id}`)
__cypressModuleCache.set(module, moduleProxy)
log(`📈 Module cache now contains ${__cypressModuleCache.size} entries`)
return moduleProxy
} catch (err) {
console.warn(`Failed to proxy module ${id}, using original which will *not* support stub/spy`, err)
return module
}
}
window.__cypressDynamicModule = function (id, importPromise, _debug = false) {
debug = _debug
return Promise.resolve(importPromise.then((module) => {
return cacheAndProxifyModule(id, module)
}))
}
window.__cypressModule = function (id, module, _debug = false) {
debug = _debug
return cacheAndProxifyModule(id, module)
}
| cypress/npm/vite-plugin-cypress-esm/client/moduleCache.js/0 | {
"file_path": "cypress/npm/vite-plugin-cypress-esm/client/moduleCache.js",
"repo_id": "cypress",
"token_count": 2378
} | 44 |
export const Mod = {
async fetcher () {
import('./mod_2').then((mod) => {
document.querySelector(`[data-cy-root]`)!.innerHTML = `<h1>${mod.greeting}</h1>`
})
},
run () {
window.setTimeout(() => {
this.fetcher()
}, 2000)
},
}
| cypress/npm/vite-plugin-cypress-esm/cypress/component/fixtures/mod_1.ts/0 | {
"file_path": "cypress/npm/vite-plugin-cypress-esm/cypress/component/fixtures/mod_1.ts",
"repo_id": "cypress",
"token_count": 122
} | 45 |
# i18n example
* For JSON-only, see [TranslatedJSONMessage.vue](TranslatedJSONMessage.vue) and its test in [spec.js](spec.js)
* From i18n support loading, see [TranslatedI18nMessage.vue](TranslatedI18nMessage.vue) and its test in [spec.js](spec.js)

**Note:** the `vue-i18n-loader` requires a webpack rule, see Webpack config in the root folder.
| cypress/npm/vue/cypress/component/advanced/i18n/README.md/0 | {
"file_path": "cypress/npm/vue/cypress/component/advanced/i18n/README.md",
"repo_id": "cypress",
"token_count": 141
} | 46 |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 2