Check email body using cypress mailhog - cypress

I'm trying to check if the email body contains, for example, a username, but i get this error saying that the value is undefined
it.only('User info', () => {
const email= cy.mhGetMailsBySubject('Your account is now confirmed')
.mhFirst().mhGetBody().should('contain', 'Thanks for the verification')
email.should('contain', 'username')
})
its.Body
CypressError Timed out retrying after 4000ms: cy.its()
errored because your subject is: undefined. You cannot access any
properties such as Body on a undefined value.
If you expect your subject to be undefined, then add an assertion such
as:
cy.wrap(undefined).should('be.undefined')
Is there a better way to do it?

Don't use the return value of the command, instead chain another assertion like this:
const username = 'Fred'
cy.mhGetMailsBySubject('Your account is now confirmed')
.mhFirst().mhGetBody()
.should('contain', 'Thanks for the verification')
.and('contain', username)

Related

NEAR FunctionCallError(HostError(GuestPanic { panic_msg: "panicked at 'Failed to deserialize input from JSON.: Error(\"the account ID is invalid\",

Via CLI, this works: NEAR_ENV=testnet near view dev-1643292007908-55838431863482 nft_tokens_for_owner '{"account_id": "hatchet.testnet"}' and produces the expected result.
I'm now trying to do the same thing via near-api-js but am getting:
Unhandled Runtime Error
Error: Querying [object Object] failed: wasm execution failed with error: FunctionCallError(HostError(GuestPanic { panic_msg: "panicked at 'Failed to deserialize input from JSON.: Error(\"the account ID is invalid\", line: 1, column: 17)', src/contract/nft.rs:65:1" })).
{
"error": "wasm execution failed with error: FunctionCallError(HostError(GuestPanic { panic_msg: \"panicked at 'Failed to deserialize input from JSON.: Error(\\\"the account ID is invalid\\\", line: 1, column: 17)', src/contract/nft.rs:65:1\" }))",
"logs": [],
"block_height": 81208522,
"block_hash": "5vWcrkVjshewYgLZTTHTZgLN7SF3qpYPovnPUUM1ucBt"
}
Call Stack
JsonRpcProvider.query
node_modules/near-api-js/lib/providers/json-rpc-provider.js (123:0)
async Account.viewFunction
node_modules/near-api-js/lib/account.js (366:0)
I've tried multiple totally separate approaches using near-api-js, and they both result in this error.
My current approach is:
export type NFT = Contract & {
nft_mint: (args: any, gas: any, depositAmount: any) => Promise<any>; // TODO Add types
nft_token: (args: any) => Promise<any>;
nft_tokens_for_owner: (args: any) => Promise<any>;
};
export function getNftContract(account: Account) {
const contract = new Contract(
account, // the account object that is connecting
certificateContractName,
{
viewMethods: ['nft_token', 'nft_tokens_for_owner'], // view methods do not change state but usually return a value
changeMethods: ['nft_mint'], // change methods modify state
},
);
return contract;
}
async function getCertificates(accountId: string): Promise<string[]> {
const keyStore = new BrowserLocalStorageKeyStore();
const near = await getNearConnection(keyStore);
const account = new Account(near.connection, ''); // account_id not required for 'view' call
const contract = getNftContract(account);
const response = await (contract as NFT).nft_tokens_for_owner({ account_id: accountId });
console.log({ account, accountId, response });
return []; // TODO
}
I'm using testnet, and the accountId I'm passing is hatchet.testnet.
This was a good lesson for me.
I started looking at the source code of https://docs.rs/near-sdk/3.1.0/src/near_sdk/json_types/account.rs.html#63 and https://docs.rs/near-sdk/3.1.0/src/near_sdk/environment/env.rs.html#816-843
I homed in on that "The account ID is invalid" error message.
But I knew I was passing a valid account ID.
It turns out the problem had nothing to do with NEAR. It was a Next.js / React problem:
My component's account_id was temporarily empty and trying to call nft_tokens_for_owner too soon (i.e. before account_id had been populated with a value).

cypressError :You attempted to make a chai-jQuery assertion on an object that is neither a DOM object or a jQuery object

im trying to check if the respone body of a request to auth0 returns an object which contains an attribute access_toke.
this is my code:
When("I attemt to login with currect user credentials", () => {
cy.intercept("https://punct-development.eu.auth0.com/oauth/token").as(
"token"
);
cy.loginWith({ email: email, password: password });
cy.wait("#token");
});
Then("Im succesfully logged in", () => {
cy
// .wait(14000)
.get("#token")
.its("response")
.should("have.property", "body")
.then((body) => {
expect(body).to.have.attr("access_token");
});
this is the tep where it fails, as you can see im getting the response body-
expected { Object (access_token, id_token, ...) } to have attribute access_token
but when trying to verify it has an attribute access_token im getting the following error()-
The chai-jQuery assertion you used was:
> attr
The invalid subject you asserted on was:
> Object{5}
To use chai-jQuery assertions your subject must be valid.
This can sometimes happen if a previous assertion changed the subject.
cypress/integration/Login/login.ts:29:28
27 | .should("have.property", "body")
28 | .then((body) => {
> 29 | expect(body).to.have.attr("access_token");
| ^
30 | });
31 | });
32 | ```
[test run screenshot][1]
[1]: https://i.stack.imgur.com/F5fRC.png
any help will be much appreciated!
I think chai uses .property while cypress uses .attr. you can use the following chain because of the a .should() command returns the object it asserts, not the original element of the chain
cy
// .wait(14000)
.get("#token")
.its("response")
.should("have.property", "body")
.should('have.attr', "access_token")

How to mock or spy on recaptcha in Jasmine

I added recaptcha-v2 in my Angular6 forms. How do I unit-test the form? I want to test that the form under test is invalid if recaptcha isn't clicked and also the form gets submitted if recaptcha is clicked.
The test I have written so far is
fit('it should emit form values if both username and password fields in the login form are correctly filled', () => {
const loginComponent = component;
spyOn(loginComponent.formOutputEvent, 'emit');
const formControls = loginComponent.loginForm.controls;
const email = 'test#test.com';
const password = 'testpassword';
formControls['userName'].setValue(email);
formControls['password'].setValue(password);
formControls['recaptcha'].setValue({}); //what value to set here?
loginComponent.loginFormSubmitted();
expect(loginComponent.formOutputEvent.emit).toHaveBeenCalledWith(new LoginFormValues(email, password));
});
I am getting error Expected spy emit to have been called with [ LoginFormValues({ username: 'test#test.com', password: 'testpassword', recaptcha: '' }) ] but actual calls were [ LoginFormValues({ username: 'test#test.com', password: 'testpassword', recaptcha: Object({ }) }) ].
Interesting, the following works even though LoginFormValues expects the 3rd argument to be of type string but {} isn't
expect(loginComponent.formOutputEvent.emit).toHaveBeenCalledWith(new LoginFormValues(email, password,{}));
But this fails because {}.toString(). gets converted to [Object object].
expect(loginComponent.formOutputEvent.emit).toHaveBeenCalledWith(new LoginFormValues(email, password,{}.toString));
I am still waiting for better answer

ApplePay completeMerchantValidation fails

We have a site example.com behind ssl that runs a page with ApplePay.
We've got a server side that returns a Merchant Session that looks like the following:
{"epochTimestamp":1581975586106,"expiresAt":1581979186106,"merchantSessionIdentifier":"SSH8E666B0...","nonce":"1239e567","merchantIdentifier":"...8557220BAF491419A...","domainName":"example.com","displayName":"ApplePay","signature":"...20101310f300d06096086480165030402010500308..."}
We receive this response in session.onvalidatemerchant as a string and convert it to a Json Object and pass to session.completeMerchantValidation.
As a result we get the following error:
Code: "InvalidAccessError"
Message: "The object does not support the operation or argument"
We run the following code on our page:
.....
session.onvalidatemerchant = (event) => {
const validationURL = event.validationURL;
getApplePaySession(validationURL).then(function (response) {
try {
let resp = JSON.parse(response);
session.completeMerchantValidation(resp);
} catch (e) {
console.error(JSON.stringify(e));
}
});
};
....
Additional questions:
Is the object described above a "correct" Merchant Session opaque that needs to be passed to completeMerchantValidation or it's missing some fields?
Is this object needs to be passed as is or it needs to be base64 encoded?
Does it need to be wrapped into another object?
Any help or lead is greatly appreciated.

Angular 2 HttpClient error body

I'm using the new (4.3) HttpClient in angular to POST data to my backend server:
this.httpClient.post<View>(`/path`, data).subscribe(
(view: View) => console.log("Success"),
(error: HttpErrorResponse) => {
console.log(error)
this.errorMessage = <any>error.error;
});
);
This call generates an (expected) error (409), but for some reason, the logged error does not contain the body of the error sent from the server. I can see the status code, but the error.error field, which should contain the response body is missing. Anyone have any ideas what could be wrong?
I've tested the backend call using curl, and can see the response body from the server.
Is your error body coming back as JSON or un-formatted text/other? I had a similar problem until i realized the body returned with the error result was a simple string. I had to change the call to something similar to this (forgive the lack of type-safety here):
this.http.post('http://address', body, { responseType: 'text' })
.subscribe(data => {
this.result = data['value'];
this.router.navigate(['/route']);
}, (error: HttpErrorResponse) => {
this.error = error.error;
this.router.navigate(['/error']);
});
This is a known bug in angular which is throwing an exception during the json parsing and not populating the error field:
https://github.com/angular/angular/pull/18466

Resources