testcafe icon indicating copy to clipboard operation
testcafe copied to clipboard

Provide the capability to add custom actions to the test controller

Open AlexanderMoskovkin opened this issue 9 years ago • 18 comments

Provide the capability to add custom actions to the test controller or chain methods that contain a test controller chain.

Custom Actions

Suppose the following test code:

const appPage = new AppPage();
test('log in', async t => {
    await t
        .typeText(appPage.loginInput, 'MyLogin')
        .typeText(appPage.passwordInput, 'Pa$$word')
        .click(appPage.signInButton)
        .expect(appPage.logInMsg.textContent).eql('Logged In');
});

With custom actions, you will be able to rewrite this test as follows:

test('log in', async t => {
    await t
        .logIn(appPage)
        .expect(appPage.logInMsg.textContent).eql('Logged In');
});

(from here: https://testcafe-discuss.devexpress.com/t/use-custom-actions-on-test-controller/228)

Chain Page Model Methods

Assume the following page model:

import { Selector, t } from 'testcafe';

export class Shop {
    constructor() {
        this.coffeeElement = 'a.coffee';
        this.teaElement = 'a.tea';
    }

    async makeCoffee() {
        await t.click(Selector(this.coffeeElement));
    }

    async makeTea() {
        await t.click(Selector(this.teaElement));
    }
}

In test code, you will be able to call these methods in a chain.

const shop = new Shop();

await shop
    .makeCoffee()
    .makeTea();

(from here: https://testcafe-discuss.devexpress.com/t/how-to-chain-pagemodel-methods/313)

AlexanderMoskovkin avatar Jun 14 '17 07:06 AlexanderMoskovkin

Might a simpler alternative be to add a apply() action that takes a function as its argument, and then calls that function with the controller as its argument? Then there would be no risk of polluting the controller's API, and we could all factor out whatever we'd like into separate functions, at least provided we only want to do sync calls.

stefanfisk avatar Aug 19 '18 14:08 stefanfisk

It's already possible with function composition :) You can use smth like this:

test('can login', pipe(
  attemptsTo(login('[email protected]', '1234567')),
  expectsTo(see(Dashboard.container))
))

stalniy avatar Sep 09 '18 19:09 stalniy

Just thinking out loud here but it looks like a custom action could be implemented as a subset of the current Role behaviour where a chain of actions are applied when using .useRole(roleX).

Let's imagine we have a similar .useAction(customAction) function and the custom actions would look something like this

const customAction = Action( async(t) => { 
    await t
        .expect(something).ok(…)
        .click(Selector(x))
        .typeText('xyz')
        …
}
// Or just
async function(t){ 
    await t …
}

This would provide consistency with current API and wouldn't clutter the t object with our custom methods while still providing good facilities to execute them in the chain.

I could so how in a more mature project an internal library of actions could be procured so the individual tests are much higher level.

Hultner avatar Nov 27 '19 13:11 Hultner

Any updates on this?

orihomie avatar Apr 15 '20 10:04 orihomie

Once we get any results, we will post them here.

AlexSkorkin avatar Apr 16 '20 06:04 AlexSkorkin

Bumping this, we've been looking for a way to do this with our testcafe suite @wistia, and we'd love to see this merged! If there's anything we can do to help here, let us know!

qrush avatar Jun 12 '20 20:06 qrush

Is there any update on this since feature?

Benyon avatar Nov 19 '20 15:11 Benyon

@Benyon, We have no updates at the moment.

arubtsov avatar Nov 20 '20 08:11 arubtsov

Another point for discussing this feature: Using Promise subclasses as return values for re-evaluating functions is bad in modern JS. Since if you return an instance of a Promise subclass from async function, it will be awaited automatically inside the engine and wrapper in a regular Promise.

> B = class extends Promise {}
[class B extends Promise]
> x = (async () => new B(resolve => resolve()))()
Promise { <pending> }
> x instanceof B
false

This is already especially bad for people using TestCafe and the promise-function-async TypeScript-ESlint rule. Since ClientFunctions returns extended Promises and the rule can auto-fix your code, using it can turn reexecutable promises into regular promises, practically disabling Smart Assertions and in some cases even completely breaking your test scenario if it is written with chained actions.

AndreyBelym avatar May 31 '21 13:05 AndreyBelym

would really like that feature! :)

magic-m-johnson avatar Jun 14 '21 07:06 magic-m-johnson

This feature would be gold 🥇 My tests would look awesome. ✨

sergiubologa avatar Sep 15 '21 06:09 sergiubologa

Definitely would be nice as a few of our tests can be quite long and chaining within single models would make things a lot cleaner.

Matenko avatar Dec 13 '21 23:12 Matenko

Having a feature such as this would be great when using POM. Without this, I have to break the test chain often which produces messy code. A simple function that just executes whatever is passed to it would make it much easier.

Current:

    await t
        .click(Page.Inventory.El.ItemAddRemoveButton)
        .expect(Page.Inventory.El.ItemAddRemoveButton.innerText).eql('REMOVE')
        .expect(Page.Navbar.El.ShoppingCartBadge.innerText).eql('1')
        .click(Page.Navbar.El.ShoppingCartButton);
    await Page.Cart.ItemExist(item);
    await t.click(Page.Cart.El.CheckoutButton)
    await Page.Checkout.EnterInfo(person);
    await Page.Checkout.ItemExist(item);
    await t.click(Page.Checkout.El.FinishButton)
        .expect(Page.Checkout.El.CompleteHeader.innerText).eql('THANK YOU FOR YOUR ORDER');

Ideal (using .run as example non-existant function)

    await t
        .click(Page.Inventory.El.ItemAddRemoveButton)
        .expect(Page.Inventory.El.ItemAddRemoveButton.innerText).eql('REMOVE')
        .expect(Page.Navbar.El.ShoppingCartBadge.innerText).eql('1')
        .click(Page.Navbar.El.ShoppingCartButton)
        .run(Page.Cart.ItemExist(item))
        .click(Page.Cart.El.CheckoutButton)
        .run(Page.Checkout.EnterInfo(person)
        .run(Page.Checkout.ItemExist(item)
        .click(Page.Checkout.El.FinishButton)
        .expect(Page.Checkout.El.CompleteHeader.innerText).eql('THANK YOU FOR YOUR ORDER');

nedwdev avatar Jan 28 '22 15:01 nedwdev

Release v2.1.1-alpha.3 addresses this.

github-actions[bot] avatar Dec 15 '22 12:12 github-actions[bot]

I'm not sure why I seem to be the only one on the Internet who ran into this problem, but I kept getting ReferenceError: Selector is not defined in my custom action. The solution is to put this at the top of your .testcaferc file:

const { Selector } = require("testcafe");

Maybe this'll save someone time in the future.

DanKaplanSES avatar Jul 09 '23 08:07 DanKaplanSES

Hi @DanKaplanSES,

This is how Node.js works: you need to import the Selector class before using it.

miherlosev avatar Jul 11 '23 06:07 miherlosev

This is how Node.js works: you need to import the Selector class before using it. @miherlosev

True. You mean require, though right? I tried import and it errored (maybe because it was in a cjs file and not a js file? Although I thought node.js uses CommonJS by default anyway, so I wouldn't expect that to make a difference).

DanKaplanSES avatar Jul 13 '23 05:07 DanKaplanSES

Hi @DanKaplanSES,

It is the same. import is used in ESM and require is used in CommonJS modules, but they serve the same goal - import one module to another. In the config file, you need to use require because TestCafe doesn't support the ESM format in the config. In tests, you can use both ways.

Aleksey28 avatar Jul 14 '23 07:07 Aleksey28