I'm using react-select in my application for implementing CSS styleable dropdowns. Also, I'm using Playwright for automatic testing want to be able to select an option from one of these dropdowns using Playwright. How to?
By trial and error, I came up with this.
import { Page, ElementHandle } from "#playwright/test"
export default async function reactSelect(page: Page, instanceId: string, optionText: string) {
const innerDetailWithKnownId = await page.waitForSelector(`#react-select-${id}-live-region`)
const select = await parentElement(innerDetailWithKnownId)
await select!.click()
const option = await page.waitForSelector(`#react-select-${instanceId}-listbox div:text('${optionText}')`)
await option.scrollIntoViewIfNeeded()
await option.click()
}
function parentElement(element: ElementHandle<any>) {
return element.$("xpath=..")
}
Here instanceId should match the value you used as instanceId for the actual react-select in your JSX code.
Here's the solution I come up with using "react-select": "5.4.0".
Note that you need to place an id my_react_select on your select for this to work
const selectOption = async (page: Page, optionText: string) => {
await page.locator('#my_react_select').click()
await page.locator(`.react-select__option:text("${optionText}")`).click()
}
Related
I want to use pressKey() to trigger the F1 or other function key.However,the pressKey seems like don't have this ability to finish what I want.
I see someone report the same question here,and in it,one of the solution they gave is like:
const pressF5 = ClientFunction(() => {
var event = new KeyboardEvent('keydown', { key: 'F5' });
document.dispatchEvent(event)
});
await pressF5();
(I have modified it to F5)
I've try this,the pressF5 work(I don't actually know if it work or not,cause it didn't gave error) but it didn't refresh the page.It just gave me test pass message.Did I use it wrong or is there anyway to trigger the function key?
Thanks in advance if anyone can help!
Edit 10/18
I have something like this:
import {Selector} from 'testcafe';
import {ClientFunction} from 'testcafe';
fixture`KEY FN`
.page`https://en.key-test.ru/`
const pressF2 = ClientFunction (() => {
const event1 = new KeyboardEvent('keydown', { code: 'F2' });
document.dispatchEvent(event1)
})
const pressF3 = ClientFunction (() => {
const event1 = new KeyboardEvent('keydown', { code: 'F3' });
document.dispatchEvent(event1 )
})
test('KEY_FN', async t => {
await t
.maximizeWindow()
.wait(3000)
await t .eval(() => location.reload(true))
await t .wait(3000)
await pressF2()
await t .wait(3000)
await pressF3()
await t
.wait(3000)
});
the site is use on testing which key you press.And the below code works as I think,it detect I press F2 and F3
I do press the key with testcafe,but how to manage to let the site have like if I press F1,it show the specific function(for example,if you press F1 on google,it will pop out a help support page)
As I mentioned earlier, system events like help calls or DevTools are not part of a web application and therefore are not built into TestCafe. However, some of them you can imitate. So, you've already used a function that is equivalent to F5 reload:
await t.eval(() => location.reload(true));
If you want to call up help, then, in Chrome, you can use
await t.navigateTo('https://support.google.com/chrome/?p=help&ctx=keyboard');
In my "/yourPage" route, my handler is trying to fetch "/api/joke" from my local database. I get "URL not found" error. Since Fresh is server rendered, I'd like to get all the data I need when loading the first time.
This works fine when fetching after initial load (like with a button).
As per its documentation, it should work fine, and does for any API that is not in its own repository.
Any way I can make this work? Am I thinking of this the wrong way?
The fetch inside my handler:
routes/yourPage.ts
export const handler: Handlers = {
async GET(req, ctx) {
const joke = await getJokes()
return ctx.render(joke);
},
};
/routes/api/joke.ts
const JOKES = [
"Why do Java developers often wear glasses? They can't C#.",
"A SQL query walks into a bar, goes up to two tables and says “can I join you?”",
];
export const handler = (_req: Request, _ctx: HandlerContext): Response => {
const randomIndex = Math.floor(Math.random() * JOKES.length);
const body = JOKES[randomIndex];
return new Response(body);
};
Pretty old post, but this is the first StackOverflow Google result when you try to search for API calling in Fresh Framework.
I am assuming you imported inside routes/yourPage.ts the handler from /routes/api/joke.ts as this:
import { handler as getJokes } from "./api/joke.ts";
Inside routes/yourPage.ts you also have to extract the text/json from the response before using it:
export const handler: Handlers = {
async GET(_req, _ctx) {
const response = getJokes(_req, _ctx);
const jokeText = await response.text();
return _ctx.render(jokeText);
},
};
Then you can use the response in your page as:
export default function Home({ data }: PageProps) { //...
Documentation here:
https://fresh.deno.dev/docs/getting-started/fetching-data
HomePage:
class homePage {
get pageHeader() { return $('//h1[contains(text(),"Best")]'); }
get pagesubHeader() { return $('div.banner-text-content>p.sub-text'); }
get supportLink() { return $('//li/span[contains(text(),"Support")]') }
HomeElement Page:
const homePage = require("../Pages/homePage")
describe("Home Page Elements handle", function () {
it("Verify HomePage Elements", async function () {
// await browser.url('https://www.freshworks.com/');
let text =homePage.pageHeader.getText();
console.log(text);
})
})
Error:
Home Page Elements handle Verify HomePage Elements
homePage.pageHeader.getText is not a function
}
module.exports = new homePage();
You use async, so this tells me you are working with WebdriverIO Async mode. This means, all the functions will mostly return a promise.
So proper way of doing it is that you need to await for the browser/element functions:
const pageHeader = await homePage.pageHeader;
const text = await pageHeader.getText();
console.log(text);
Remember, $, $$ and basically any functions of the browser or of the element are promises in async mode, so essentially, you attempted to "getText()" or "click()" on a promise object.
I am trying to use an automated build system that detects changes (feat/fix) and updates semver automatically (repo-cooker).
In order for this to work, I need to query the current "latest" version from the market place repository. Is there any proper way to do this without scraping the SVG badge (which seems safer than scraping a page) ?
const got = require('got')
const RE = /<title>.*v([0-9\.]+)<\/title>/
const BASE_URL = 'https://vsmarketplacebadge.apphb.com/version-short'
async function getVersion(ext) {
const response = await got(`${BASE_URL}/${ext}.svg`)
const re = RE.exec(response.body)
if (re) {
return re[1]
} else {
throw new Error(`Could not scrape for ${ext} version.`)
}
}
async function main() {
console.log(await getVersion('pawijs.vscode-pawi'))
}
main()
I'm having the following issue and hope someone could help me on it:
Fetch is not working on the first load (nor on reloads). It only works when on the client-side (when I move between routes).
I've read that watchQuery could help but didn't understand why and how to use it.
<script>
export default {
async fetch() {
const userId = await this.$nuxt.context.store.state.auth.authUser.userId
await this.$store.dispatch('case/fetchMyCases', userId.uid)
await this.$store.dispatch('case/fetchMyPendingCases', userId.uid)
...
It doesn't work even if I import and use firebase/auth directly.
<script>
import * as firebase from 'firebase/app'
import 'firebase/auth'
export default {
async fetch() {
const userId = await firebase.auth().currentUser
await this.$store.dispatch('case/fetchMyCases', userId.uid)
await this.$store.dispatch('case/fetchMyPendingCases', userId.uid)
...
Does anyone have any tips for it? I'd really appreciate it.
Thanks!
After literally 3 days searching/testing, I finally found out why I was having this issue.
The problem was that I simply put async/await for fetch but didn't put async/await for the actions itself. Therefore, my getter (in computed) was getting the store state before the dispatches have been finished.
Thanks, everyone!
Warning: You don't have access of the component instance through this inside fetch because it is called before initiating the component (server-side).
async fetch({ store }) {
await store.dispatch('case/fetchMyCases')
await store.dispatch('case/fetchMyPendingCases')
}
If you need parameter:
async fetch({ store, params }) {
await store.dispatch('case/fetchMyCases', params.uid)
await store.dispatch('case/fetchMyPendingCases', params.uid)
}
I gave an example of id. The name of the parameter depends on the name of your page.
_id => params.id
_uid => params.uid
_slug => params.slug
...
Yes, You must put async/await on actions.
async automatically returns a promise
If you don't need the value, in this case, don't anything return.
export const Actions = {
async fetchUsers() {
// It will return automatically promise
await this.$axios.get('API')
}
}
// If you need returne value
// First way
export const Actions = {
async fetchUsers() {
// It will return promise and value
return await this.$axios.get('API')
}
}
// Second way
export const Actions = {
async fetchUsers() {
// It will return promise and value
const response = await this.$axios.get('API')
return response;
}
}