I have below simple code which work fine in Android but in IOS await doesn't work.
const CheckAsyncfucntion = async () => {
console.log('Before Await execution');
const authenticateuser = await newUser(registration_id); // return true or false
console.log('After Await Execution => ', authenticateuser);
}
in andorid it work fine. but in ios both the log are getting print with undefined value of authenticateuser. and after that newUser value is getting return.
Any Lead in this will be appreciated.
Am using IOS smiulator iphone12 iOS 15.0
I guess the problem is in the function newUser.
My iOS simulator works just fine with any async functions like below.
const CheckAsyncfucntion = async () => {
console.log('Before Await execution');
// return true or false from Promise
const authenticateuser = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve(true);
}, 2000);
});
console.log('After Await Execution => ', authenticateuser);
};
CheckAsyncfucntion();
Related
I have created a small React app and I want to test it using Playwright component testing
I have 3 components: App -> ChildComponent -> ChildChildComponent
I want to render (mount) the ChildComponent directly, and make assertions on it, but when I do that, some ContextApi functions that are defined in the App in the normal flow, are now undefined as the App component is not part of the component test.
So i'v trying to render the ChildComponent together with a face ContextApi Provider and pass mocks of those undefined functions, and then I get an infinite render loop for some reason.
How can I go about this, as this use case is typical in react component test.
Here is the test with all my failed mocking attempts separated:
test.only("validate CharacterModal", async ({ page, mount }) => {
const data = ['some-mocked-irrelevant-data']
// const setCurrentCharacter = () => {};
// const setIsCharacterModalOpen = () => {};
// const setCurrentCharacterMocked = sinon.stub("setCurrentCharacter").callsFake(() => {});
// const setIsCharacterModalOpenMocked = sinon.stub("setCurrentCharacter").callsFake(() => {});
// const setCurrentCharacter = jest.fn();
// const setIsCharacterModalOpen = jest.fn();
// const setCurrentCharacter = (): void => {};
// const setIsCharacterModalOpen = (): void => {};
// const setIsCharacterModalOpen = (isCharacterModalOpen: boolean): void => {};
const AppContext = React.createContext<any>(null);
await page.route("**/users*", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(data),
});
});
const component = await mount(
<AppContext.Provider value={{ setCurrentCharacterMocked, setIsCharacterModalOpenMocked }}>
<CharacterModal />
</AppContext.Provider>
);
expect(await component.getByRole("img").count()).toEqual(4);
});
The beforeMount hook can be used for this. I recently added docs about this: https://github.com/microsoft/playwright/pull/20593/files.
// playwright/index.jsx
import { beforeMount, afterMount } from '#playwright/experimental-ct-react/hooks';
// NOTE: It's probably better to use a real context
const AppContext = React.createContext(null);
beforeMount(async ({ App, hooksConfig }) => {
if (hooksConfig?.overrides) {
return (
<AppContext.Provider value={hooksConfig.overrides}>
<App />
</AppContext.Provider>
);
}
});
// src/CharacterModal.test.jsx
import { test, expect } from '#playwright/experimental-ct-react';
import { CharacterModal } from './CharacterModal';
test('configure context through hooks config', async ({ page, mount }) => {
const component = await mount(<CharacterModal />, {
hooksConfig: { overrides: 'this is given to the context' },
});
});
I try to write E2E test with playwright but something is wrong.
When I was initialize the test, test passed but actually, block did not go inside the bracket.
It also passes the test when I enter the wrong selector.
The code is below:
import { _electron as electron } from 'playwright';
import { test, expect, ElectronApplication, Page, BrowserContext, Locator } from '#playwright/test';
test.describe('Add Connection', async() => {
let electronApp: ElectronApplication;
let firstWindow: Page;
let context: BrowserContext;
test.beforeAll(async() => {
electronApp = await electron.launch({ args: ['.']} );
const appPath = await electronApp.evaluate(async({ app }) => {
return app.getAppPath();
});
console.log(appPath);
});
test('Try Connection', () => {
electronApp.on('window', async(page) => {
await page.getByTestId('settings').click({delay: 1000});
await page.getByTestId('connection').click({delay: 1000});
});
});
test.afterAll(async() => {
await electronApp.close();
});
});
I haven't seen enough documentation about E2E testing on Electron. How can we write a test where we can go to different pages by clicking on the buttons?
I solved this problem. The inside of 'Try Connection' test doesn't work because electronApp.on() is a callback function.
To write ElectronJS & Playwright test I choose these steps:
I got a Page object (firstWindow) after that I clicked on the buttons and went to the place I wanted to test.
The final code:
import { _electron as electron } from 'playwright';
import { test, expect, ElectronApplication, Page } from '#playwright/test';
test.describe('Add Connection', async() => {
let electronApp: ElectronApplication;
let firstWindow: Page;
test.beforeAll(async() => {
electronApp = await electron.launch({ args: ['.']} );
firstWindow = await electronApp.firstWindow();
});
test('Try Connection', async() => {
await firstWindow.title();
await firstWindow.click('xpath=//*[#id="sidemenu-container"]/a[3]', {delay: 1500});
await firstWindow.click('xpath=//*[#id="***"]/app-settings/div/div[1]/button[1]', {delay: 1500});
await firstWindow.click('xpath=//*[#id="***"]', {delay: 1500});
await firstWindow.getByPlaceholder('***').fill('emir connection');
await firstWindow.locator('#***').selectOption({label: '***'});
await firstWindow.click('xpath=//*[#id="***"]', {delay: 2000});
// for the wait, (fake click)
await firstWindow.click('xpath=//*[#id="***"]', {delay: 7000});
});
test.afterAll(async() => {
await electronApp.close();
});
});
I am using foreach to run the test for multiple users.
I can access the variable from foreach inside of beforeAll, but does not work inside of test
the following line does not get the value as expected, i verified i have value for that column in the .csv
await page.locator('#searchByCode').fill(${user.Code}); // Does not Work , get undefined
import fs from 'fs';
import path from 'path';
import { test, expect, Page } from '#playwright/test';
import { parse } from 'csv-parse/sync'; //requires https://www.npmjs.com/package/csv-parse
const users = parse(fs.readFileSync(path.join(__dirname, '../users.csv')), {
columns: true,
skip_empty_lines: true
});
//Want test inside of describe to run in serial mode
test.describe.configure({ mode: 'serial' });
test.use({ viewport: { width: 600, height: 900 } }); //Affects all Tests
let page: Page;
users.forEach(user => {
console.log(user.Email);
test.describe(`Login for user ${user.Email}`, () => {
test.beforeAll(async ({ browser }) => {
// Create page once and sign in.
page = await browser.newPage();
await page.goto('https://XXXXXXX.com');
await page.fill("#logInEmail",`${user.Email}`); **//This one works**
//find password text(#loginInPassword) and enter password
await page.fill('#loginInPassword', `${user.Password}`); **//This one works**
await Promise.all([
page.waitForNavigation(/*{ url: 'https://getinline.net/' }*/),
page.locator('#loginSignIn').click()
]);
});
test.afterAll(async () => {
await page.close();
});
test('SearchBusinessByCode', async ({ browser }, testInfo) => {
await page.locator('#searchByCode').fill(`${user.Password}`); **// Does not Work , get undefined**
await page.locator('button', { hasText: 'Search' }).click();
});
});
}); //forEach
I am currently using #react-native-community/cameraroll currently and i am trying to get images and albums on my ios device.
The following is the code I tried
CameraRoll.getPhotos({})
.then((res) => {
console.log("result 1", res)
}).catch((error) => { })
CameraRoll.getAlbums({})
.then((res) => {
console.log("result 2", res)
})
.catch((error) => {
console.log(error);
});
result 1 and result 2 give the following result
result 1 {"edges": [], "page_info": {"has_next_page": false}}
result 2 []
Any help would be appreciated. The same code works well on Android.
I tried with a lot of combinations and the one below worked for the ios device -
CameraRoll.getPhotos({ first: 5000, assetType: 'Photos' })
.then((result) => {
const tempBuckets = [];
var edgesArr = result.edges;
}).catch((error) => { })
The result here contains an edges array that has all the images and their respective properties.
The count '5000' is an arbitrary number i have used, without which the result array obtained was empty.
the solution is to add permission before request like
async function hasAndroidPermission() {
const permission =
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
const hasPermission = await PermissionsAndroid.check(permission);
if (hasPermission) {
return true;
}
const status = await PermissionsAndroid.request(permission);
return status === 'granted';
}
and use like this
const Gallery = async () =>{
if (Platform.OS === "android" && !(await hasAndroidPermission())) {
return;
}
CameraRoll.getAlbums({assetType: "Photos", albumType: "All"})
.then((r:any) => {
console.log("images-->",r)
})
.catch((err:any) => {
//Error Loading Images
console.log("err->",err)
});
}
I'm trying to screenshot a website using puppeteer, and on slow sites I receive a TimeoutError.
In this case, I'd like to get the screenshot of the current page state - is this possible? if so, how?
Code sample:
const puppeteer = require('puppeteer');
let url = "http://...";
let timeout = 30000;
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page
.goto(url, {waitUntil: 'load', timeout: timeout}).then(async () => {
await page
.screenshot({path: 'example.png'})
.catch(error => console.error(error));
})
.catch(error => {
if (error.name === "TimeoutError") {
// -----> calling await page.screenshot({path: 'example.png'}) gets stuck
} else {
console.error(error);
}
});
await browser.close();
})();
Don't use browser.close when using puppeteer in development, as this may cause the browser closed and puppeteer crashed.
const puppeteer = require('puppeteer')
let url = "https://www.tokopedia.com"
let filename = 'timeout.png'
let timeoutNum = 30000
;(async () => {
const browser = await puppeteer.launch({
headless: false
});
const [page] = await browser.pages ()
page.setViewport ({ width: 1366, height: 768 })
try {
await page.goto(url, {waitUntil: 'networkidle0', timeout: timeoutNum}).then(async () => {
await page.screenshot({ path: 'example.png', fullPage: true })
})
} catch (error) {
if (error.name === "TimeoutError") {
console.log (error.name)
console.log (`Screenshot saved as ${filename}`)
await page.screenshot({ path: filename, fullPage: true })
} else {
console.log (error)
}
}
})()