Assertion fails but test is successful - reactjs

This is crucial think in cypress.io and does not work (Assertion fails but test is successful). Full code below. I have tried to rewrite my code many times, without success. Installed latest NPM, latest Node.JS. Deleted node_modules and reinstalled dependencies.
/* eslint-disable no-undef */
describe("Contact us form", () => {
beforeEach(() => {
cy.visit("/");
cy.contains("Contact us").click();
cy.location().should(loc => {
expect(loc.pathname).to.eq("/contact-us");
});
});
it.only("Fill Contact us form - error 500", () => {
cy.server();
cy.route({
method: "POST",
url: "/api/v1/email/contact-us",
status: 500,
response: {}
}).as("sendMessage");
cy.getTestElement("ContactUs__form__container").within(() => {
cy.get("#users").then(users => {
const user = users.admin;
cy.get("#name")
.type(user.name)
.should("have.value", user.name);
cy.get("#email")
.type(user.email)
.should("have.value", user.email);
cy.get("#phone")
.type(user.phone)
.should("have.value", user.phone);
const message = Cypress.config("testVars").testMessage;
cy.get("#message")
.type(message)
.should("have.value", message);
});
cy.get("button:first").click(); // "Send message"
});
cy.wait("#sendMessage");
cy.get("#alert-dialog-description").contains("My App");
});
});

Known issue?
https://github.com/cypress-io/cypress/issues/3497
Are you running the latest cypress (3.1.5)?

As far as I know, you cannot automate captcha

Related

How to In App Purchases with ReactJS and Capacitor

I am using Capacitor to generate both the IOS and Android apps (not using Iconic) - this works well, but we are trying to implement IAP (for IOS only at this stage) and cannot figure it out.
I have followed various guides (https://ionicframework.com/docs/native/in-app-purchase-2 and https://purchase.cordova.fovea.cc/ and https://capacitorjs.com/docs/guides/in-app-purchases) but simply cannot get it working with React (not React Native)
Can someone point me in the right direction, or provide sample code?
You didn't describe what is going wrong, but here's a basic configuration that works for me on iOS.
I'm only including the part about the store:
index.tsx
import { IAPProduct, InAppPurchase2 } from '#ionic-native/in-app-purchase-2';
const startStoreEventListeners = () => {
if (isPlatformMobile()) {
document.addEventListener(
'deviceready',
() => {
const store = InAppPurchase2;
// Needed to use IAP + cordova plugins.
// Set debug messages.
// Default.
store.verbosity = store.QUIET;
// store.verbosity = store.DEBUG;
store.register([
{
id: subMonthly,
type: store.PAID_SUBSCRIPTION,
},
{
id: subAnnual,
type: store.PAID_SUBSCRIPTION,
},
]);
// Upon approval, verify the receipt.
store.when(subMonthly).approved((product: IAPProduct) => {
product.verify();
});
store.when(subAnnual).approved((product: IAPProduct) => {
product.verify();
});
// Upon receipt validation, mark the subscription as owned.
store.when(subMonthly).verified((product: IAPProduct) => {
product.finish();
});
store.when(subAnnual).verified((product: IAPProduct) => {
product.finish();
});
// Track all store errors
store.error((err: Error) => {
debugLog('Store Error', JSON.stringify(err));
});
// https://billing-dashboard.fovea.cc/setup/cordova
store.validator =
'https://validator.fovea.cc/v1/validate?appName=secret';
store.refresh();
startIonic();
},
false,
);
} else {
startIonic();
}
};
startStoreEventListeners();
serviceWorker.unregister();
Note that #ionic-native packages are deprecated and need to be converted.

cypress - TypeError cannot set property 'status' of undefined

I am trying to use cypress on my UI testing each time I got TypeError cannot set property 'status' of undefined error in a different place
describe('cats app', () => {
beforeEach(() => {
// Cypress starts out with a blank slate for each test
// so we must tell it to visit our website with the `cy.visit()` command.
// Since we want to visit the same URL at the start of all our tests,
// we include it in our beforeEach function so that it runs before each test
cy.visit(Cypress.env('host'))
})
it('login to cats', () => {
// clear local storage
cy.clearLocalStorage()
cy.get('#email').focus().type(Cypress.env('email'))
.should('have.value', Cypress.env('email'))
cy.screenshot("login-email")
cy.get('#password').focus().type(Cypress.env('password'))
.should('have.value', Cypress.env('password'))
cy.screenshot("login-password")
cy.get("#login").click({force: true})
// to ensure login is working
cy.get("#TicketsNav").should('be.visible')
cy.screenshot("TicketsNav")
})
})
I tried to handle the issue as it happens most of the time while typing by adding and use these commands
Cypress.Commands.add(
'paste',
{
prevSubject: true,
element: true,
},
($element, text) => {
const subString = text.substr(0, text.length - 1);
const lastChar = text.slice(-1);
cy.get($element)
.click()
.then(() => {
$element.text(subString);
$element.val(subString);
cy.get($element).type(lastChar);
});
}
);
Cypress.Commands.overwrite('type', (originalFn, subject, text, options = {}) => {
options.delay = 20
return originalFn(subject, text, options)
})
also, I tried to force the chrome browser
cypress run --browser chrome
but I am still getting that error if different places

React Native S3 image upload returns "Stream Closed" using XHR

After updating React Native version to latest 0.63.2 and trying to upload the image to S3 bucket XHR returns error Stream Closed image upload was working fine with version 0.61.5
The Code
uploadProfile({ variables: { filetype: mime } }).then(
({ data: { uploadUserProfile } }) => {
const { presignedUrl, url } = uploadUserProfile;
console.log('presignedUrl', { presignedUrl, url });
// uploading to s3 bucket
const xhr = new XMLHttpRequest();
xhr.open('PUT', presignedUrl);
xhr.onreadystatechange = async function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
updateAccount({
variables: {
data: {
profile: url,
},
},
});
} else {
if (/Request has expired/g.test(xhr.response))
Toast({ message: 'slow network connection' });
else {
console.log({
response: xhr.response,
responseText: xhr.responseText,
status: xhr.status,
});
Toast({ message: 'internal server error' });
await report({
error: {
response: xhr.response,
responseText: xhr.responseText,
status: xhr.status,
},
}); // reporting error
}
}
}
};
xhr.setRequestHeader('Content-Type', mime);
xhr.send({ uri: path, type: mime });
setLoading(false);
},
);
When the user wants to upload a profile image first App send a request to the server and get return the pre-signed URL and upload from client-side this how App was working.
I upgraded Flipper to version 0.51.2 and it worked for me.
Go to android/gradle.properties and add this line
FLIPPER_VERSION=0.52.1
You should have the following lines in your android/app/build.gradle
dependencies {
// ....
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
// ...
}
upgrading flipper version solves the issue for me, If upgrading flipper version doesn't solve for you then try this solution.
Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.
My workaround to make this work is commenting outline number 43
38 NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39 NetworkingModule.setCustomClientBuilder(
40 new NetworkingModule.CustomClientBuilder() {
41 #Override
42 public void apply(OkHttpClient.Builder builder) {
43 // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44 }
45 });
46 client.addPlugin(networkFlipperPlugin);
in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java
found this answer link

Setting and accessing environment variables in Jest and Puppeteer

I am trying to find a way to set the browser configurations for Puppeteer once so that I do not have to do it for every
test case.
Currently, this is the structure I'm working with:
jest.config.js
process.env.BROWSER_PATH='<PATH_TO_CHROME>/chrome.exe';
module.exports = {
preset: "jest-puppeteer",
globals: {
URL: "http:localhost:3000",
HEADLESS: (process.env.NODE_ENV==='development' ||
process.env.NODE_ENV==='production'
? true : false
)
},
testMatch: [
"**/test/**/*.test.js"
],
verbose: true
}
jest-puppeteer.config.js
module.exports = {
launch: {
headless: HEADLESS,
slwoMo: process.env.SLOWMO ? process.env.SLOWMO : 0,
devtools: false,
executablePath: process.env.BROWSER_PATH,
}
}
browserTest.js
describe('Browser Test', () => {
// This test has 2 asserts
test('Browser Popup: successful', async () => {
console.log("[BrowserTest] headless:", HEADLESS);
try {
const browser = await puppeteer.launch({
// headless: process.env.HEADLESS == 'true'? true:false,
// executablePath: process.env.BROWSER_PATH,
isMobile: false,
});
const page = await browser.newPage();
await page.goto(URL, {
waitUntil: 'domcontentloaded'
});
page.once('load', () => console.log('[BrowserPopup] Page loaded!'));
await new Promise(resolve => setTimeout(resolve, 7500));
await browser.close();
} catch (e) {
console.log('Err: ', e);
}
}, timeout);
});
The idea is that if I have headless and executablePath in the launch configurations (in jest-puppeteer.config.js), then shouldn't puppeteer pick it up from there? Why do I have to re-declare it when launching the browser in my test case?
The alternative I thought of was that if I cannot do this, then I want to be able to replicate this behavior in the process.env.HEADLESS as shown in the first line jest.config.js. I'd remove it from the globals declaration of the config file. This method does not work either.
Question: Is there a singular place I could put this so that I don't have to keep declaring this? The HEADLESS state depends on its environment it is being executed in.
Note: Currently, this throws an error because jest-puppeteer.config.js cannot see jest.config.js. So its a 'HEADLESS is not defined' error. After fixing it, it threw another error that Chrome was not defined. So I had to put that in the puppeteer.launch({}) parameters as well. Which leads me to believe that jest-puppeteer.js isn't really doing anything, since it can't see headless or executablePath.
Note: I run the tests using jest --config=jest.config.js. This works because I can use the global variable in a successful test run. Thanks for all the help!

ReactJS + Cypress E2E testing

a quick question for anyone with React + Cypress experience - writing my first set of E2E tests and here's whats bugging me :
cy.visit('http://movinito.docker.localhost:3000/company/subcontractors');
works, but
cy.visit('/company/subcontractors');
doesn't work as expected (redirects me to the dashboard after login and stays there when I try to assert a pathname includes 'subcontractors').
my baseUrl in the cypress.json is
{"baseUrl": "http://react_frontend.movinito.docker.localhost:3000"}
and it generally works (in case that was what you suspected).
I would like to use the shorter, nicer version cy.visit('/company/subcontractors'); instead of the long winded retype of the baseUrl...
Might be important to add that prior to the .visit I use a
cy.request('POST', 'http://movinito.docker.localhost/user/login?_format=json', {name,pass});
to [successfully] log in... As I said the whole thing works but I can't make use of the baseUrl and have to use the .visit command with the full environement based url...
Here is the [working] full test code
describe('Subcontractors section', ()=> {
it('renders properly', ()=> {
const { name, pass } = {name: 'info#batcave.com', pass: '123#456'}
cy.request('POST', 'http://movinito.docker.localhost/user/login?_format=json', {
name,
pass
});
cy.visit('http://movinito.docker.localhost:3000/company/subcontractors');
//
// I want to replace the above line with cy.visit('/company/subcontractors')
//
cy.location('pathname').should('include', '/company/subcontractors');
cy.get('[data-cy=page-title]').should('have.text', 'Subcontractors');
})
});
hmm, I read the documentation about visit() and request(), this should work to:
describe('Subcontractors section', ()=> {
it('renders properly', ()=> {
cy.visit({
url: 'http://movinito.docker.localhost/user/login?_format=json',
method: 'POST',
body {
name,
pass
}
})
cy.visit('/company/subcontractors')
cy.location('pathname').should('include', '/company/subcontractors')
})
});
// cypress.json
{
"baseUrl": "http://react_frontend.movinito.docker.localhost:3000"
}

Resources