.mouseButtonDown/Up won't work in custom-commands NightwatchJS - nightwatch.js

When I use .mouseButtonDown/Up in test then it's work, but when I want to add it to my custom command I have typeError "this.move to element(...).mouseButtonDown is not a function"
my custom-command looks like:
resize: function (Xoffset, Yoffset) {
this.api.pause(1000);
return this
.moveToElement("#widget_resize", 5, 5)
.mouseButtonDown(0)
.moveToElement("#widgets_container", Xoffset, Yoffset)
.mouseButtonUp(0);
}
code in test which works:
browser
.moveToElement("span.react-resizable-handle", 5, 5)
.mouseButtonDown(0)
.moveToElement("main.site-container", 1630, 620)
.mouseButtonUp(0)

I always pass the client as an argument to any of my custom functions that require any interaction with the browser. I cannot recall why. So, if I am not mistaken, the below should work. I would welcome an explanation as to why it works - or why it's a bad idea - by any stackoverflow user:
resize: function (client, Xoffset, Yoffset) {
this.api.pause(1000);
return
client.moveToElement("#widget_resize", 5, 5)
client.mouseButtonDown(0)
client.moveToElement("#widgets_container", Xoffset, Yoffset)
client.mouseButtonUp(0);
}
I'm expecting to get downvoted for the reasons why this is not best practice, but I could use the humility and more importantly to better understand this stuff.

did you try insert ".pause(500)" ?
resize: function (Xoffset, Yoffset) {
this.api.pause(1000);
return this
.moveToElement("#widget_resize", 5, 5)
.mouseButtonDown(0)
.pause(500)
.moveToElement("#widgets_container", Xoffset, Yoffset)
.mouseButtonUp(0);
}

Related

Cypress returning Synchronous value within Async command?

So I think this is probably me mixing up sync/async code (Mainly because Cypress has told me so) but I have a function within a page object within Cypress that is searching for customer data. I need to use this data later on in my test case to confirm the values.
Here is my function:
searchCustomer(searchText: string) {
this.customerInput.type(searchText)
this.searchButton.click()
cy.wait('#{AliasedCustomerRequest}').then(intercept => {
const data = intercept.response.body.data
console.log('Response Data: \n')
console.log(data)
if (data.length > 0) {
{Click some drop downdowns }
return data < ----I think here is the problem
} else {
{Do other stuff }
}
})
}
and in my test case itself:
let customerData = searchAndSelectCustomerIfExist('Joe Schmoe')
//Do some stuff with customerData (Probably fill in some form fields and confirm values)
So You can see what I am trying to do, if we search and find a customer I need to store that data for my test case (so I can then run some cy.validate commands and check if the values exist/etc....)
Cypress basically told me I was wrong via the error message:
cy.then() failed because you are mixing up async and sync code.
In your callback function you invoked 1 or more cy commands but then
returned a synchronous value.
Cypress commands are asynchronous and it doesn't make sense to queue
cy commands and yet return a synchronous value.
You likely forgot to properly chain the cy commands using another
cy.then().
So obviously I am mixing up async/sync code. But since the return was within the .then() I was thinking this would work. But I assume in my test case that doesn't work since the commands run synchronously I assume?
Since you have Cypress commands inside the function, you need to return the chain and use .then() on the returned value.
Also you need to return something from the else branch that's not going to break the code that uses the method, e.g an empty array.
searchCustomer(searchText: string): Chainable<any[]> {
this.customerInput.type(searchText)
this.searchButton.click()
return cy.wait('#{AliasedCustomerRequest}').then(intercept => {
const data = intercept.response.body.data
console.log('Response Data: \n')
console.log(data)
if (data.length) {
{Click some drop downdowns }
return data
} else {
{Do other stuff }
return []
}
})
}
// using
searchCustomer('my-customer').then((data: any[]) => {
if (data.length) {
}
})
Finally "Click some drop downdowns" is asynchronous code, and you may get headaches calling that inside the search.
It would be better to do those actions after the result is passed back. That also makes your code cleaner (easier to understand) since searchCustomer() does only that, has no side effects.
you just need to add return before the cy.wait
here's a bare-bones example
it("test", () => {
function searchCustomer() {
return cy.wait(100).then(intercept => {
const data = {text: "my data"}
return data
})
}
const myCustomer = searchCustomer()
myCustomer.should("have.key", "text")
myCustomer.its("text").should("eq", "my data")
});

Is there any recommended way to return property values through getters?

I'm playing a bit with writing php extensions and trying to figure out what would be the best way to return class private property value through method (registered by the extension of course).
Here is what I have so far:
PHP_MINIT_FUNCTION(uamqp_connection) {
// class initialization
zend_declare_property_bool(this_ce, "boolValue", sizeof("boolValue") - 1, 0, ZEND_ACC_PRIVATE);
}
And then method:
PHP_METHOD(Test, getBool)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(zval_get_long(zend_read_property(this_ce, getThis(), "boolValue", sizeof("boolValue") -1, 1, NULL)));
}
I'm not sure about this zval_get_long passed later to RETURN_BOOL, is that something that could be considered valid way? Is there any easier/more obvious solution? This one seems to work but I still dont feel confident about it.

How to stub Fluture?

Background
I am trying to convert a code snippet from good old Promises into something using Flutures and Sanctuary:
https://codesandbox.io/embed/q3z3p17rpj?codemirror=1
Problem
Now, usually, using Promises, I can uses a library like sinonjs to stub the promises, i.e. to fake their results, force to resolve, to reject, ect.
This is fundamental, as it helps one test several branch directions and make sure everything works as is supposed to.
With Flutures however, it is different. One cannot simply stub a Fluture and I didn't find any sinon-esque libraries that could help either.
Questions
How do you stub Flutures ?
Is there any specific recommendation to doing TDD with Flutures/Sanctuary?
I'm not sure, but those Flutures (this name! ... nevermind, API looks cool) are plain objects, just like promises. They only have more elaborate API and different behavior.
Moreover, you can easily create "mock" flutures with Future.of, Future.reject instead of doing some real API calls.
Yes, sinon contains sugar helpers like resolves, rejects but they are just wrappers that can be implemented with callsFake.
So, you can easily create stub that creates fluture like this.
someApi.someFun = sinon.stub().callsFake((arg) => {
assert.equals(arg, 'spam');
return Future.of('bar');
});
Then you can test it like any other API.
The only problem is "asynchronicity", but that can be solved like proposed below.
// with async/await
it('spams with async', async () => {
const result = await someApi.someFun('spam).promise();
assert.equals(result, 'bar');
});
// or leveraging mocha's ability to wait for returned thenables
it('spams', async () => {
return someApi.someFun('spam)
.fork(
(result) => { assert.equals(result, 'bar');},
(error) => { /* ???? */ }
)
.promise();
});
As Zbigniew suggested, Future.of and Future.reject are great candidates for mocking using plain old javascript or whatever tools or framework you like.
To answer part 2 of your question, any specific recommendations how to do TDD with Fluture. There is of course not the one true way it should be done. However I do recommend you invest a little time in readability and ease of writing tests if you plan on using Futures all across your application.
This applies to anything you frequently include in tests though, not just Futures.
The idea is that when you are skimming over test cases, you will see developer intention, rather than boilerplate to get your tests to do what you need them to.
In my case I use mocha & chai in the BDD style (given when then).
And for readability I created these helper functions.
const {expect} = require('chai');
exports.expectRejection = (f, onReject) =>
f.fork(
onReject,
value => expect.fail(
`Expected Future to reject, but was ` +
`resolved with value: ${value}`
)
);
exports.expectResolve = (f, onResolve) =>
f.fork(
error => expect.fail(
`Expected Future to resolve, but was ` +
`rejected with value: ${error}`
),
onResolve
);
As you can see, nothing magical going on, I simply fail the unexpected result and let you handle the expected path, to do more assertions with that.
Now some tests would look like this:
const Future = require('fluture');
const {expect} = require('chai');
const {expectRejection, expectResolve} = require('../util/futures');
describe('Resolving function', () => {
it('should resolve with the given value', done => {
// Given
const value = 42;
// When
const f = Future.of(value);
// Then
expectResolve(f, out => {
expect(out).to.equal(value);
done();
});
});
});
describe('Rejecting function', () => {
it('should reject with the given value', done => {
// Given
const value = 666;
// When
const f = Future.of(value);
// Then
expectRejection(f, out => {
expect(out).to.equal(value);
done();
});
});
});
And running should give one pass and one failure.
✓ Resolving function should resolve with the given value: 1ms
1) Rejecting function should reject with the given value
1 passing (6ms)
1 failing
1) Rejecting function
should reject with the given value:
AssertionError: Expected Future to reject, but was resolved with value: 666
Do keep in mind that this should be treated as asynchronous code. Which is why I always accept the done function as an argument in it() and call it at the end of my expected results. Alternatively you could change the helper functions to return a promise and let mocha handle that.

Need correct call to Promise reduce (when.reduce )

I have a processor function that takes a "cmd" object and returns a promise where the resolution is the same "cmd" object passed in (with a response key added). reduce here is when.reduce
reduce = require('when').reduce;
//return processor(cmds[0])
return reduce(cmds, function(processor, cmd) {
Debug.L1('running processor for component ', cmd.component)
return processor(cmd)
})
.then(cmds => {
Debug.L1('cmds with responses\n', cmds)
let response = cmds.map(cmd => {
return cmd.response
})
console.log('the complete response is\n', response)
});
This does nothing, it does get to the .then but the array of promises never fires, never see the Debug running processor...
If I run just a single processor it works great cmd[0], cmds[1], etc.
return processor(cmds[0])
//return reduce(cmds, function(processor,cmd) {
// Debug.L1('running processor for component ', cmd.component)
// return processor(cmd) })
What am I missing here? Their api and wiki examples aren't giving me any insight.
IMPORTANT UPDATE:
The answer below does work but throws unhandled rejection errors. The culprit is the when library. It seems no longer active and has not been updated since node 6. I switched to bluebird and it works fine without any change to the code outlined below.
I'm still not sure what you are looking for, but it might be
reduce(cmds, function(responses, cmd) {
return processor(cmd).then(function(response) {
responses.push(response); // or whatever
return responses;
});
}, []).then(function(responses) {
…
});
Before trying to understand when.reduce, you might want to have a look at the non-promise array reduce.

How to efficiently remove first element from a selection?

I have a page that displays some data using d3.js. Due to the heavy processing load, when the page load it freezes the browser for a few seconds.
I have determined that this "browser locking" behavior is due mostly to a line of the form:
selection.attr('d', linefn);
...where selection contains around 10K items.
I would like to replace this line with something like
function process_rest () {
if (selection.size() > 0) {
var next_item = first(selection); // function first() is hypothetical!
next_item.attr('d', linefn);
selection = rest(selection); // function rest() is hypothetical!
setTimeout(process_rest, 100);
return;
}
finish_up();
}
setTimeout(process_rest, 100);
I'm looking for an efficient way to implement either first and rest. My very naive guess would be something like:
function first(selection) {
return d3.select(selection[0][0]);
}
function rest(selection) {
selection[0] = selection[0].slice(1);
return selection;
}
...but, AFAIK, this is going "behind the API", or at least feels like it. Is there an "official" (i.e. documented) way to achieve the same result?
EDIT: deleted the shift variant (it's safer not to update selection until after the processing of the first element has been successfully completed).
You can simply use .each():
selection.each(function(d, i) {
setTimeout(function() { d3.select(this).attr("d", linefn); }, i * 100);
});

Resources