Giter Club home page Giter Club logo

testcafe-testing-library's Introduction

testcafe-testing-library

ox

Testcafe selectors and utilities that encourage good testing practices laid down by dom-testing-library.

Read the docs | Edit the docs


testcafe-testing-library version downloads MIT License semantic-release

All Contributors PRs Welcome Code of Conduct Dependabot Status Discord

Watch on GitHub Star on GitHub Tweet

The problem

You want to use dom-testing-library methods in your Testcafe tests.

This solution

This allows you to use all the useful dom-testing-library methods in your tests.

Table of Contents

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's devDependencies:

npm install --save-dev @testing-library/testcafe

Usage

Usage Docs

Other Solutions

I'm not aware of any, if you are please make a pull request and add it here!

Contributors

Thanks goes to these wonderful people (emoji key):


Ben Monro

πŸ“– πŸ’» ⚠️ πŸš‡ πŸ€”

Kent C. Dodds

πŸš‡ πŸ€” πŸ’»

Mikhail Losev

πŸ’» πŸ’¬

Maarten Van Hoof

πŸ’»

Katsuya Hino

πŸ’»

Ned Schwartz

πŸ“–

Matej Ε nuderl

πŸ’» ⚠️

Tim Pinington

πŸ’» ⚠️

Nils Hartmann

πŸ›

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT

testcafe-testing-library's People

Contributors

allcontributors[bot] avatar benmonro avatar dependabot-preview[bot] avatar dependabot[bot] avatar dobogo avatar hagendorn avatar imgbot[bot] avatar meemaw avatar michaeldeboey avatar mrtnvh avatar nickmccurdy avatar timmak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

testcafe-testing-library's Issues

Type Error: Argument of type '{ name: string; }' is not assignable to parameter of type 'MatcherOptions'.

Describe the bug
The issues is in the types file options argument not all option take the base interface MatcherOptions some take extend options as seen here https://github.com/testing-library/dom-testing-library/blob/master/types/queries.d.ts

To Reproduce

import { getByRole, within } from "@testing-library/testcafe";

getByRole("cell", { name: `test` })

Expected behavior
The option types should match those queires in dom testing library

Text is not normalized according to testing-library's normalization documentation

Describe the bug
When using testcafe-testing-library, text normalization does not work as documented (emphasis mine):

Normalization

Before running any matching logic against text in the DOM, DOM Testing Library automatically normalizes that text. By default, normalization consists of trimming whitespace from the start and end of text, and collapsing multiple adjacent whitespace characters within the string into a single space.

To Reproduce
Put this content into your html file:

<h1 data-testid="header">
  My Header
</h1>

And put this code into your test file:

import { screen } from '@testing-library/testcafe';
import { Selector } from 'testcafe';
//...
    await t.expect(screen.queryByTestId('header').innerText)
    .eql('My Header')

Expected behavior
This test passes.

Actual behavior
This test fails due to whitespace differences:

   1) AssertionError: expected '\nMy Header\n' to deeply equal 'My Header'

      + expected - actual

      -
      -My Header
      +My Header

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: Headless Chrome
  • Version: Version 115.0.5790.171 (Official Build) (64-bit)

Additional context
As a workaround, I could manually trim the innerText, but according to the documentation, I shouldn't have to.

Although I haven't tested this, this bug implies that custom normalizers passed into the query functions will be ignored.

Unable to use any of the selectors from @testing-library/testcafe in testcafe tests

Describe the bug
Unable to use @testing-library/testcafe selectors in tests.

To Reproduce
Steps to reproduce the behavior:

  1. generate a new repo with testcafe
  2. add the following test
import { screen } from "@testing-library/testcafe";

fixture`Getting Started`.page`https://devexpress.github.io/testcafe/example`;

test("first test", async (t) => {
// also attempted to 
// const group = screen.getByRole('group', {  name: /your name:/i});
// within(group).getByRole('textbox');

  await t
    .typeText(screen.getByRole("textbox", { name: /name/i }), "John Smith")
    .click(screen.getByRole("button", { name: /submit/i }));

  await t
    .expect(
      screen.getByRole("heading", {
        name: /thank you, john smith!/i,
      }).exists
    )
    .ok();
});
  1. Add testcaferc.json to root
{
  "clientScripts": [
    {
      "module": "@testing-library/dom/dist/@testing-library/dom.umd.js"
    }
  ],
  "browsers": [
    "chrome:headless"
  ],
  "src": "tests/*.test.ts"
}
  1. add this script to package.json "testcafe": "testcafe chrome:headless"

  2. Run test yarn testcafe | npm run testcafe

  3. See error

Getting Started
 βœ– first test

   1) An error occurred in Selector code:

      Error: Cannot call method 'getByRole' of undefined

Expected behavior
Expected to be able to use getBy findBy queryBy (none of these options worked)

Desktop (please complete the following information):

  • OS: [macOS 12.4] (Apple M1 Chip)
  • Browser [chrome]
  • Version [e.g. 103.0.5060.53]

Additional context
Add any other context about the problem here.

FindAll, getAll, queryAll do not return arrays when used on table elements

Describe the bug
I have a similar HTML:

<html>
<head>
<body>
<div>
<div>
<div>
<div>
<table data-test-id="table-global-top">
<tbody>
<tr>
<tr>
<tr>
<tr>
<td data-test-id="row-points">
</tr>
...
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</head>
</html>

Essentially, I have a number of "row-points" elements and when I am trying to get, find or query all of them, the length of my array is always 0 (it is not returned at all). If I try to use a normal query, like findByTestId or getByText, the library says that more than 1 element is found.

To Reproduce
Steps to reproduce the behavior:

  1. Use the html above.
  2. Use the next piece of code to get the rows elements:
findRowByTablePosition = rowPosition => screen.findAllByTestId('row-points')[rowPosition];
console.log(await this.findRowByTablePosition(1).textContent);

Expected behavior
The text of the 2nd element in the array is logged in the console.

Actual behavior
1) TypeError: Cannot read property 'textContent' of undefined

Desktop (please complete the following information):

  • OS: macOS
  • Browser: Chrome
  • Version 109.0.5414.87

EDIT:

Apparently, the problem is evident also within a helper method in a Page class, like this one:

async waitForTableCalculation(counter = 0) {
    if (counter >= 100 || (await this.someElement.visible)) {
        console.log(await findRowByTablePosition(1).textContent);
        if ((await this.someOtherElement.textContent) === '18') {
            return;
        }
    }

The console.log line here returns 1) TypeError: Cannot read property 'textContent' of undefined. However, it returns the same error with a Selector that is proved working when defined in the constructor of this Page (BoardPage in this case) and used in the test code, as normal. Like this:

this.boardRows = screen.findAllByTestId('row-position');
...

 await t
     .typeText(BoardPage.searchField, 'random String')
     .pressKey('enter')
     .expect(BoardPage.boardRows.count)
     .eql(1)

Error running test from sub-package in monorepo

I have a monorepo where testcafe and testcafe-testing-library files are in the top-level node_modules with links to the cli entry script installed in packages/sub-package/.bin. When I run testcafe tests that use testdafe-testing-library from the sub-package they fail with

$ testcafe chrome testcafe/**/*.test.js
ERROR Cannot prepare tests due to an error.

Error: ENOENT: no such file or directory, open 'node_modules/dom-testing-library/dist/dom-testing-library.umd.js'
    at Object.<anonymous> (/Users/eschiebel/exempt/src/canvas-lms/node_modules/testcafe-testing-library/dist/index.js:23:41)
    at Object.origExt [as .js] (/Users/eschiebel/exempt/src/canvas-lms/node_modules/testcafe/src/compiler/test-file/api-based.js:83:21)
    at Object.<anonymous> (/Users/eschiebel/exempt/src/canvas-lms/packages/canvas-rce/testcafe/RCEWrapper.test.js:21:1)
    at Function._compile [as _execAsModule] (/Users/eschiebel/exempt/src/canvas-lms/node_modules/testcafe/src/compiler/test-file/api-based.js:50:13)
    at ESNextTestFileCompiler._execAsModule [as _runCompiledCode] (/Users/eschiebel/exempt/src/canvas-lms/node_modules/testcafe/src/compiler/test-file/api-based.js:149:42)
    at ESNextTestFileCompiler._runCompiledCode [as execute] (/Users/eschiebel/exempt/src/canvas-lms/node_modules/testcafe/src/compiler/test-file/api-based.js:173:21)
    at ESNextTestFileCompiler.execute (/Users/eschiebel/exempt/src/canvas-lms/node_modules/testcafe/src/compiler/test-file/api-based.js:179:21)
    at compile (/Users/eschiebel/exempt/src/canvas-lms/node_modules/testcafe/src/compiler/index.js:98:31)
    at Compiler._getTests (/Users/eschiebel/exempt/src/canvas-lms/node_modules/testcafe/src/compiler/index.js:94:66)
    at _getTests (/Users/eschiebel/exempt/src/canvas-lms/node_modules/testcafe/src/compiler/index.js:110:35)

Invitation to move to testing-library org

It's up to you, but if you'd like, you're welcome to transfer this repository to the testing-library organization on GitHub. This will give your project more credibility as part of the testing-library family of projects with a unified mission of tools which help people avoid testing implementation details.

Again, totally up to you. I just want you to know we appreciate all you've done and you're welcome to join us if you like.

Property 'exists' does not exist on type 'NodeSnapshot'.

Describe the bug
Following the documentation, I tried to write the following test

const main = Selector('main[role="main"]');
const dialog = Selector('div[role="dialog"]');

signin = within(main).queryByText("Sign in");
google = within(dialog).queryByText(/Google/i);

test("user clicks the sign-in button", async (t) => {
  await t
    .expect(google.exists)
    .notOk("Modal should not be opened")
    .takeScreenshot()
    .click(signin)
    .expect(google.exists)
    .ok("Modal is opened")
    .takeScreenshot();
}

When running tests, I get the following error pointing on the notOk line

   1) An error occurred in Selector code:

      TypeError: Expected container to be an Element, a Document or a DocumentFragment but
      got undefined.

And when trying to console.log the value of await googe.exists, I get

ERROR Cannot prepare tests due to the following error:

Error: TypeScript compilation failed.
/path/to/e2e/signin.ts (7, 27): Property 'exists' does not exist on type 'NodeSnapshot'.

Expected behavior

I thought from reading the examples that @testing-library/testcafe queries would return a TestCafe Selector object, making properties like exists available.

Here's a working test without using testing-library

  const main = Selector('main[role="main"]');
  const dialog = Selector('div[role="dialog"]');

  const signin = main.find("button").withText("Sign in");
  const google = dialog.find("button").withText("Google");

  await t
    .expect(google.exists)
    .notOk("Modal should not be opened")
    .takeScreenshot()
    .click(signin)
    .expect(google.exists)
    .ok("Modal is opened")
    .takeScreenshot();

testcafe-testing-library's custom Selector didn't work in testcafe page model

Hi,

when I use custom Selector (getBy, getByAll ...) provided by testcafe-testing-library in testcafe's page model that throw me an error. So I'm obliged to use the legacy Selector in that case.

Screen Shot 2019-05-22 at 18 34 54

Here is a sample of my test :

// Error
test('should correctly handle error when a wrong password is typed', async t => {
  await loginPage.login(login, 'WRONG PASSWORD');

  await t.expect(loginPage.errorWrongPassword).ok();
});

// Correct
test('should correctly handle error when a wrong password is typed ', async t => {
  await loginPage.login(login, 'WRONG PASSWORD');

  await t.expect(loginPage.errorWrongPassword2).ok();
});

Here is a sample of my page model :

import { getByTestId, getByPlaceholderText } from 'testcafe-testing-library';
import { t, Selector } from 'testcafe';

export default class LoginPage {
  constructor() {
    this.usernameInput = getByPlaceholderText(/username/i);
    this.passwordInput = getByPlaceholderText(/password/i);
    this.submitButton = getByTestId('submit');
    this.errorIsEmpty = Selector('[data-testid="error-isEmpty"]');

    // Error
    this.errorWrongPassword = getByTestId('wrong-credentials');
    // Correct
    this.errorWrongPassword2 = Selector('[data-testid="wrong-credentials"]');
  }
  async login(username, password) {
    await t
      .typeText(this.usernameInput, username)
      .typeText(this.passwordInput, password)
      .click(this.submitButton);
  }
}

Thank you for taking a look on that issue guys. πŸ‘

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://[secure]@github.com/testing-library/testcafe-testing-library.git.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


The push permission to the Git repository is required.

semantic-release cannot push the version tag to the branch master on remote Git repository with URL https://[secure]@github.com/testing-library/testcafe-testing-library.git.

Please refer to the authentication configuration documentation to configure the Git credentials on your CI environment and make sure the repositoryUrl is configured with a valid Git URL.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Error: Cannot call method 'getByPlaceholderText' of undefined

Describe the bug
I am trying to execute the below sample code and it's always throwing the same error that Cannot call method 'getByPlaceholderText' of undefined. Attached the code below.

import {
getByText,
getByPlaceholderText
} from '@testing-library/testcafe'

fixture('Google Page').page('https://opensource-demo.orangehrmlive.com/index.php/auth/login');

test("Create button", async t => {

await t.typeText(getByPlaceholderText('Username'),'admin');
await t.typeText(getByPlaceholderText('Password'),'admin123')
await t.click(getByText('LOGIN'))

});

Screenshots
Screenshot 2020-11-24 at 10 23 06 PM

After reload inside of a test error "TestingLibraryDom is not defined" thrown.

Adding testcafe-testing-library to fixture,

fixture`Foo`
  .page(constants.base)
  .beforeEach(addTestcafeTestingLibrary);

If I reload the page during a test I get an error thrown when I use a testcafe-testing-library functions in the same test.

await t.eval(() => location.reload(true));
await t
    .expect(getAllByTestId("foo")).ok()

Error thrown,

image

Use of queryByXXX vs getByXXX

If you want to assert that an element exists and you have a page that loads slowly, you have to use queryByXXX selector variants, otherwise you will get intermittent failures using getByXXX when the element is not available in time.

I burnt a fair bit of time trying to figure out why I was getting intermittent failures because
I'm new to using testing-library and had forgotten that difference. I didn't initially make the connection that the error message I was seeing from getByText was because it was throwing an exception and not allowing Testcafe to retry the selector until the element was available.

Is it worth adding an example and/or notes about this usage distinction to the documentation? Currently they only show the usage of getByXXX selectors.

Error with `within` due to transpilation error

I can not use within query because it throw an exception as see bellow:

1) SyntaxError: missing ) after argument list

      Browser: Firefox 66.0.0 / Linux 0.0.0

         44 |      return DomTestingLibrary.${queryName}(document.body, ...arguments);
         45 |      `));
         46 |});
         47 |
         48 |const within = async sel => {
       > 49 |  await (0, _testcafe.ClientFunction)(new Function(` 
         50 |    const elem = document.querySelector("${sel}");
         51 |    window.TestCafeTestingLibrary["within_${sel}"] = DomTestingLibrary.within(elem);
         52 |
         53 |    `))();
         54 |  const container = {};

         at within (/home/user/contact-list/node_modules/testcafe-testing-library/dist/index.js:49:39)
         at  (/home/user/contact-list/tests/testcafe/test.spec.js:47:58)
         at step (/home/user/contact-list/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
         at  (/home/user/contact-list/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13)
         at $$testcafe_test_run$$ZaCadmd6U$$ (/home/user/contact-list/node_modules/testcafe/src/api/test-run-tracker.js:76:16)
         at $$testcafe_test_run$$ZaCadmd6U$$ (/home/user/contact-list/node_modules/testcafe/src/api/test-run-tracker.js:76:16)



 1/1 failed (8s)

Reproduce error with this repository: https://github.com/leosuncin/contact-list/tree/testcafe-testing-library_issue-15

Other Info:
testcafe-testing-library: 1.1.1
testcafe: 1.1.4
OS: Manjaro Linux 4.19
Node: 11.14.0
Firefox: 66.0.5
Chrome: 76.0.3783

Unpredictable assertion behaviour in highly async application

Hi πŸ‘‹

We're using TestCafe in combination with testcafe-testing-library to test our highly async Electron app. I am encountering this problem where assertions like:
t.expect(queryAllByText('Surrey Quays').nth(8).exists).ok()
Sometimes fail and sometimes pass. I came across an older already closed issue (#53), covering a similar problem where slower apps do funny things using get* instead of query*.

Now, that made sense to me as get* throws and query* returns. Since a lot of items in our app appear in an asynchronous manner, that would've and should've solved our problem. Sadly enough I am still seeing these random assertion failures.

It could be that I'm missing a step or that I'm using the assertions wrong. In any circumstance, I would like to see if I can get my tests to work in a predictable manner :)

Cheers

The automated release is failing 🚨

🚨 The automated release from the undefined branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the undefined branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


The release 3.0.0 on branch master cannot be published as it is out of range.

Based on the releases published on other branches, only versions within the range >=2.1.1 <3.0.0 can be published from branch master.

The following commits are responsible for the invalid release:

  • fix: updated dom testing library (#31) (f716bfd)
  • chore: merge next to master (#30) (5e6b199)
  • docs: add vanhoofmaarten as a contributor (#27) (b63e9c0)
  • docs: add dobogo as a contributor (#25) (7f68879)

Those commits should be moved to a valid branch with git merge or git cherry-pick and removed from branch master with git revert or git reset.

A valid branch could be next.

See the workflow configuration documentation for more details.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Does testcafe-testing-library support IE11

I have used testcafe-testing-library on chrome/firefox/IE11. Chrome and Firefox all work fine but I am having these errors on IE11:

An error occurred in Selector code:Β 
TypeError: Unable to get property 'apply' of undefined or null reference

An error occurred in a script injected into the tested page:
TypeError: Unable to get property 'for' of undefined or null reference

I am wondering if testcafe-testing-library supports IE browser?

My Test:
test('Show title', async t => {
await t
.expect(getByText('title').visible)
.ok('Title is visible.');
});

Error: Cannot call method 'queryByRole' of undefined(experimentalProxyless: true)

Describe the bug
Unable to use the testing-library selector with the experimentalProxyless option of testcafe enabled, which is previously proxyless.

To Reproduce
Steps to reproduce the behavior:

  1. Clone the demo repo: https://github.com/Roy412/msw-testcafe-error/tree/testing_library_compatibility
  2. Install the packages: yarn
  3. Run the testcafe test: yarn testcafe
  4. You can see the failure with the error Error: Cannot call method 'queryByRole' of undefined

Expected behavior
The selectors should work with the experimentalProxyless option enabled.

Screenshots
Screenshot 2022-12-21 at 4 27 31 PM

Desktop (please complete the following information):

  • OS: [e.g. iOS] MacOS
  • Browser [e.g. chrome, safari] Chrome
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Note that it uses 2.2.0-rc.1 version of TestCafe. For older versions, the option name is proxyless.
Interestingly, withexperimentalProxyless option disabled, the test passes. And of course, the selectors from testcafe library work too.

testcafe-testing-library breaks TestCafe's testController.navigateTo function.

Describe the bug
If the testcafe-testing-library script has been injected into the browser, when TestCafe runs and attempts to invoke the testController.navigateTo method, the following error is thrown:

TypeError: Cannot read property 'destUrl' of null
Of course, the stack trace terminates at the invocation point in the test script rather than where destUrl is actually referenced.

If I follow the docs exactly, the full error is...

An error occurred in the '@testing-library/dom/dist/@testing-library/dom.umd.js' module injected into the tested page. Make sure that this module can be executed in the browser environment.

Error details:

TypeError: Cannot read property 'destUrl' of null

If I modify the .testcaferc.json to not inject the script as a module then I get...

An error occurred in a script injected into the tested page:

TypeError: Cannot read property 'destUrl' of null

To Reproduce
Steps to reproduce the behavior:
Please see this repo which is the minimal-reproducible-example I could create.

  1. git clone [email protected]:SamuelDavis/testing-library-testcafe-integration.git;
  2. cd testing-library-testcafe-integration;
  3. npm install;
  4. npx testcafe chrome tests.js; or via docker: docker run --rm -it -v $PWD:/mnt -w /mnt --env NODE_PATH=/mnt/node_modules testcafe/testcafe chromium tests.js;

Expected behavior
I expect the test to pass, or at least throw an error relevant to the test I've written, or provide me with more actionable feedback.

Screenshots
testcafe-testing-library failing

Additional context
It seems like it might be an underlying issue with testcafe-hammerhead.js, but the error only occurs when the testcafe-testing-library script is injected. It's also significant that the usage docs .testcaferc.json module configuration throws an error out of the box.

Selector is expected to be initialized with a function, CSS selector

After upgrading to testcafe v1.6.0 it seems that @testing-library/testcafe selectors started failing:

I can see this repo is still on v1.5.0 so it probably is not compatible with v1.6.0 yet?

import { getByPlaceholderText } from '@testing-library/testcafe';

  const searchInput = getByPlaceholderText( 'Type...');
  await t
    .expect(searchInput.exists)
    .ok('Search input exists')
    .typeText(searchInput, 'randomText');

Throws:
Screen Shot 2019-10-18 at 11 57 02 AM

Error points to the .typeText line.

Your Environment details:

  • testcafe version: 1.6.0
  • node.js version: v8.16.0
  • browser name and version: HeadlessChrome 68.0.3440

P.S.
I have also opened this issue in testcafe repo: DevExpress/testcafe#4400

testcafe useRoles are broken on 4.0.1 and 4.1.0

If I upgrade from 4.0.0 to either 4.0.1 or 4.1.0 then I get the following error from the testcafe (version 1.8.4) useRole feature:

An error occurred in a script injected into the tested page:
TypeError: Cannot read property 'destUrl' of null

I case it's helpful, my login function first goes to a logout address and then goes through the login steps.

Upgrading to 3.x broken previously working tests.

I upgraded following https://testing-library.com/docs/testcafe-testing-library/intro

Removing:
addTestcafeTestingLibrary from my test and beforeEach in the fixture.

Adding:

  "clientScripts": [
    "./node_modules/@testing-library/dom/dist/@testing-library/dom.umd.js"
  ],

With a very simple test:

test('Table Exists', async t => {
  await getByTestId('table-id').exists;
});

Now I get:

   1) Selector cannot implicitly resolve the test run in context of which it should be executed. If you need to call Selector from the Node.js API callback, pass
      the test controller manually via Selector's `.with({ boundTestRun: t })` method first. Note that you cannot execute Selector outside the test code.

I have others' but, this is the simplest example. If I downgrade to 2.x it works as expected, did I miss something?

Error: TypeScript compilation failed.

Describe the bug
After adding testcafe-testing-library to my project, I'm getting a TS compilation error:

.../node_modules/@testing-library/testcafe/dist/index.d.ts (2, 13): '=' expected.
.../node_modules/@testing-library/testcafe/dist/index.d.ts (2, 77): ';' expected.

To Reproduce
Steps to reproduce the behavior:

  1. Add testcafe-testing-library to project
  2. Execute a test
  3. See error

Expected behavior
Test should run

Screenshots
Screen Shot 2020-08-19 at 9 50 24 AM

Desktop (please complete the following information):

  • OS: Mac OS
  • Browser: Chrome
  • Version 84

Additional context
I have [email protected], [email protected]

Wait function not working as expected after testing-library-dom update

Description
New version of testing-library-dom is deprecating wait function for waitFor, breaking some existent tests using a previous version (β€œ6.14.0”).

Could be due to this change:

Previously, wait was a wrapper around wait-for-expect and used polling instead of a MutationObserver to look for changes. It is now an alias to waitFor and will be removed in a future release.

This causes the following error when trying to use the wait/waitFor function for an element that needs to appear in the browser:

         92 |  if (typeof window === 'undefined') {
       > 93 |    throw new Error('Could not find default container'); 

Steps to reproduce:

  1. Use the wait/waitFor function for an element in the page
    Example:
    await waitFor(async () => t.expect(findByRole('table')).eql(vehiclesToBeDeleted.length))

Expected behavior
Behavior of wait function is not changed and still can be used to wait for browser elements.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: macOS 10.15.7
  • Browser: Chrome
  • Version 91.0.4472.77

Additional context
The same test passes if testing-library-dom (β€œ6.14.0”) is used instead.

Error logs:

   1) Error: Could not find default container

      Browser: Chrome 91.0.4472.77 / macOS 10.15.7

         88 |exports.clearTimeout = clearTimeoutFn;
         89 |
         90 |function getDocument() {
         91 |  /* istanbul ignore if */
         92 |  if (typeof window === 'undefined') {
       > 93 |    throw new Error('Could not find default container');
         94 |  }
         95 |
         96 |  return window.document;
         97 |}
         98 |

Babel 6 errors when using react-boilerplate

Using testcafe-testing-library with react-boilerplate causes this error:

ERROR Cannot prepare tests due to an error.

ReferenceError: Using removed Babel 6 option: .resolveModuleSource - Use `babel-plugin-module-resolver@3`'s 'resolvePath' options

Steps to reproduce:

  1. Set up a react-boilerplate project (https://github.com/react-boilerplate/react-boilerplate/#quick-start).
  2. Install testcafe and @testing-library/testcafe as dependencies.
  3. Create a test file and add a test that uses a helper function from @testing-library/testcafe.
  4. Run the test with testcafe.

Unfortunately I couldn't get this work on codesandbox but here is a reproduction repo (just run the testcafe script):
https://github.com/Ronva/react-boilerplate-testcafe
Relevant changes: https://github.com/Ronva/react-boilerplate-testcafe/commit/bc1e5c5a4a379635953cd723a8e3a740d7a9e821

TypeError: Cannot read property 'destUrl' of null

Describe the bug
After including a reference to "@testing-library/dom/dist/@testing-library/dom.umd.js" in .testcaferc.json as per https://testing-library.com/docs/testcafe-testing-library/intro, tests that were successfully executing now fail with error:

- Error in fixture.beforeEach hook -
An error occurred in the '@testing-library/dom/dist/@testing-library/dom.umd.js' module injected into the tested page. Make sure that this module can be executed in the browser environment.

Error details:
TypeError: Cannot read property 'destUrl' of null

Browser: Microsoft Edge 85.0.564.51 / Windows 10

6 |
7 |/// Login/Logout workflow
8 |fixture('Login/Logout')
9 |    .beforeEach( async t => {
10 |        await t
> 11 |            .useRole(nssUser);
12 |    });
13 |
14 |/// Login & Logout
15 |test
16 |    ("Log user into & out of PodBrowser", async t => {

at <anonymous> (C:\Projects\GitHub\destURL\tests\login.js:11:14)
at <anonymous> (C:\Projects\GitHub\destURL\tests\login.js:8:1)

To Reproduce

  1. Extract the attached zipfile destURL.zip
  2. Execute testcafe edge ./tests/login.js.

Expected behavior
Login test passes.

Desktop (please complete the following information):

  • OS: Windows
  • Browser: Edge
  • Version: Version 85.0.564.51 (Official build) (64-bit)

findBy/findByAll not working with within

Describe the bug
Using a findBy and findAllBy query function on a selector returned by within throws error:

1) Function that specifies a selector can only return a DOM node, an array of nodes, NodeList, HTMLCollection, null or undefined. Use ClientFunction to
      return other values.

In my example the following works:

 const group = screen.findByRole("group", { name: "My Group" });

  await t
    .expect(
      within(group).getByRole("button", { name: "Increase B" }).exists
    )
    .ok();

while this one does not:

 const group = screen.findByRole("group", { name: "My Group" });

 await t
    .expect(
      within(group).findByRole("button", { name: "Increase B" }).exists
    )
    .ok();

It doesn't matter if I find the group with findByRole or getByRole.

To Reproduce

You can find a reproducable example at https://github.com/nilshartmann/testcafe-within. The app in this repository is a create-react-app-based example.

  1. Clone the repo
  2. yarn install
  3. yarn start
  4. in second terminal: yarn testcafe

Testfile: https://github.com/nilshartmann/testcafe-within/blob/master/testcafe/within.test.ts

Versions:

"@testing-library/testcafe": "^4.3.0",
 "testcafe": "^1.9.4"

Expected behavior

I'd expect that findBy should also work with selectors from within?

Desktop (please complete the following information):

  • OS: 10.15.7
  • Browser: firefox, chrome
  • Version Chrome 87.0.4280.67

Allow configurable debug print size with DEBUG_PRINT_LIMIT env var

Is your feature request related to a problem? Please describe.
Other testing-library libs have the ability to configure the size of the debug output by using the DEBUG_PRINT_LIMIT env variable. This doesn't seem to work with testcafe-testing-library.

Describe the solution you'd like
Allow setting DEBUG_PRINT_LIMIT to increase the size of the default debug print when selectors like getByText fail to find an element.

Describe alternatives you've considered
N/A

Additional context
N/A

findByTestId doesn't work

I have a page which makes fetch call to get list of records. I wrote below test on the page which will assert records. But fails!!

//my test

// import { Selector } from 'testcafe';
import { findByTestId } from '@testing-library/testcafe';

fixture('Stores Table Header - tests').page('http://localhost:3030/');

test('Stores table headers', async t => {
  // const findByTestId = id => {
  //   return Selector('*').withAttribute('data-testid', id); // This works
  // };

  await t
    .expect(findByTestId('table-header-name').textContent)
    .eql('Name')

    .expect(findByTestId('table-header-description').textContent)
    .eql('Description')

    .expect(findByTestId('table-header-status').textContent)
    .eql('Status')

    .expect(findByTestId('table-header-total-capacity').textContent)
    .eql('Total Capacity')

    .expect(findByTestId('table-header-used-capacity').textContent)
    .eql('Used Capacity')

    .expect(findByTestId('table-header-available-capacity').textContent)
    .eql('Available Capacity');
});

I get below error ...

1) Function that specifies a selector can only return a DOM node, an array of nodes, NodeList, HTMLCollection, null or
      undefined. Use ClientFunction to return other values.

      Browser: Chrome 66.0.3359.170 / macOS 10.13.6

          8 |  //   return Selector('*').withAttribute('data-testid', id);
          9 |  // };
         10 |
         11 |  await t
         12 |    .expect(findByTestId('table-header-name').textContent)
       > 13 |    .eql('Name')
         14 |
         15 |    .expect(findByTestId('table-header-description').textContent)
         16 |    .eql('Description')
         17 |
         18 |    .expect(findByTestId('table-header-status').textContent)

         at <anonymous>
      (/Users/pathiyu/Desktop/NCV/cloud-ui-backup/src/routes/stores/integration-test/stores-list-header.js:13:6)
         at test (/Users/pathiyu/Desktop/NCV/cloud-ui-backup/src/routes/stores/integration-test/stores-list-header.js:6:1)
         at <anonymous>
      (/Users/pathiyu/Desktop/NCV/cloud-ui-backup/node_modules/testcafe/src/api/wrap-test-function.js:17:28)
         at LiveModeTestRun._executeTestFn
      (/Users/pathiyu/Desktop/NCV/cloud-ui-backup/node_modules/testcafe/src/test-run/index.js:291:19)
         at LiveModeTestRun.start
      (/Users/pathiyu/Desktop/NCV/cloud-ui-backup/node_modules/testcafe/src/test-run/index.js:342:24)

Can someone help me please.

Support ClientFunctions for findByRole's name option

Is your feature request related to a problem? Please describe.
I had a list of buttons containing years and wanted to do a numeric comparison to a year number in a variable instead of a string comparison. findByRole's types suggest that it supports a function form of the name option and thought that would work.

However because the name function is executed on the client it loses the context necessary to work (i.e. the function cannot use any variable outside it).

Describe the solution you'd like
testcafe has an API for supporting this. Its ClientFunction API allows defining dependencies that will be passed to the ClientFunction's context.

It would be great if we could pass a ClientFunction to the name option of findByRole so we could define our own ClientFunction with any dependencies we need.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.