can't use pressKey() to trigger function key - testing

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');

Related

How to automate react-select with Playwright

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()
}

setState inside an async search

I am trying to set a stateful object with results I get from an async search and I'm getting some errors and strange behavior.
I'm using algoliasearch to run this search. Here's the code in pseudo, I can share the full code if needed, but I don't think it's important. The search works just fine and I get results (see comments below)
const [results, setResults] = useState(null);
index.search(searchQuery, {...requestOptions})
.then(({ hits }) => {
fetchedResultsArray = hits?.map((result) => {
...
return {...}
}
// console.log("fetchedResultsArray", fetchedResultsArray)
setResults(fetchedResultsArray)
).catch
It causing the app to act funny, get stuck, sometimes crash. Sometimes I get this (very long) error: Warning: Please report: Excessive number of pending callbacks: 501. Some pending callbacks that might have leaked by never being called from native code: {"1531":{"module":"NativeAnimatedModule","method":"startAnimatingNode"}...
When I comment setResults(fetchedResultsArray) and uncomment the console log before it, it prints the results and the app acts normal. Reverting back to setResults(fetchedResultsArray) and things go wrong again. I am doing something wrong/illegal, but what?
Another important thing to mention is that I'm using Expo SDK 41 beta 2.
UPDATE
Patrick, you pointed out what I am doing wrong. Let me show you in a little more depth what I do in my SearchScreen, again abbreviated:
const SearchScreen = () => {
// I get the initSearch function from a custom hook and you already see above what the function is.
const [
initSearch,
...
] = useSearch();
// Then I fire the search when the screen loaded
useLayoutEffect(() => {
if (region) {
initSearch({ searchQuery, region, filterOptions, priceOptions });
}
}, [filterOptions, initSearch, priceOptions, region, searchQuery]);
...
my custom hook is something like this:
export function useSearch() {
const [readyToAnimateAfterSearch, setReadyToAnimateAfterSearch] = useState<boolean>(false);
const [results, setResults] = useState<Result[] | null>(null);
const setAlert = useStore(useCallback((state) => state.setAlert, []));
const setProgressBarVisible = useStore(useCallback((state) => state.setProgressBarVisible, []));
const [radius, setRadius] = useState<number>(0);
const initSearch = useCallback(
async ({ searchQuery, region, filterOptions, priceOptions, loadMore = false }) => {
...
},
[results, setResults, setAlert, setProgressBarVisible]
);
return [
initSearch,
results,
setResults,
radius,
readyToAnimateAfterSearch,
setReadyToAnimateAfterSearch,
] as const;
Could you please suggest an alternative way to run this as an answer. No need to go into details, just so I get the flow of how you would handle this. Thank you!
My main issue was me using results inside the initSearch function, instead of using a stateUpdater function and removing results from the deps array.

Focus event unit test doesn't works in Vuejs / Jest

I want to create a unit test for two events, on focus and on blur.
I am using vueJS and jest.
handleFocus(event) {
if (this.blured === true)
if (event.relatedTarget !== null) {
this.blured = event.relatedTarget.className
.toString()
.includes("datepicker");
} else this.blured = false;
}
That's what i tried, but the method seems not to be called
beforeEach(() => {
mocks = {
$t: jest.fn()
};
});
it("calls 'handleFocus' on focus", async () => {
const wrapper = mount(CxpDatepicker, {
mocks,
localVue
});
const input = wrapper.find("input");
wrapper.vm.handleFocus = jest.fn();
input.trigger("focus");
await localVue.nextTick();
expect(wrapper.vm.handleFocus).toHaveBeenCalled();
});
Please help pe to find the solution.
I understand I am very late to reply, but if you or anyone else still needs to know,
Try following to invoke your event:
input.element.dispatchEvent(new FocusEvent('focus'));
Instead of
input.trigger("focus");
I was also not able to invoke it. So I tried this way, and it worked for me.

How to stop multiple Firebase events callback on(Value,snapshot)

I am new to firebase. I want to get realtime data when a user click on any pushKey. When i click on another node i get previous node data also.I dont know where to use ref.off('value',listener). please help me out. Anyhelp will be appreciated
export const fetchCurrentCircleLocation = pushKey => {
return async dispatch => {
let ref = firebase.database().ref(Circles/${pushKey}/members);
let listener = await ref.on("value", snapshot => {
// console.log("circleLocation", snapshot.val());
dispatch({
type: FETCH_CURRENT_GROUP_CIRCLE_LOCATION,
payload: snapshot.val()
});
});
};
};
Try using once. It will go through your database items only once. You don't need to remove listener.
ref.once("value", function (snapshot) {
snapshot.forEach((child) => {
console.log(child.val())
});
});

Async/await t test codes are not working in in beforeEach of TestCafe

When I tried to use beforeEach in TestCafe, a function with some test codes inside of it seems not working properly.
I am using doLogin in all different fixtures and tests.
Not working
const doLogin = async (t) => {
const login = new Login();
await t
.maximizeWindow()
.typeText(login.emailInput, accounts.EMAIL_SUCCESS, { replace: true, paste: true })
.expect(login.emailInput.value).eql(accounts.EMAIL_SUCCESS, 'check an email')
.typeText(login.passwordInput, accounts.PASSWORD, { paste: true })
.click(login.loginButton);
};
fixture`App > ${menuName}`
.page`${HOST}`
.beforeEach(async (t) => {
// This function is called
// but tests inside the function were not run
doLogin(t)
});
Working Case with a fixture
fixture`App > ${menuName}`
.page`${HOST}`
.beforeEach(async (t) => {
const login = new Login();
// But this case is working.
await t
.maximizeWindow()
.typeText(login.emailInput, accounts.EMAIL_SUCCESS, { replace: true, paste: true })
.expect(login.emailInput.value).eql(accounts.EMAIL_SUCCESS, 'check an email')
.typeText(login.passwordInput, accounts.PASSWORD, { paste: true })
.click(login.loginButton);
});
Working Case with calling from a test
test(`show all ${menuName} menu's components`, async (t) => {
// When I added a function directly into a test function then it worked.
doLogin(t);
// some codes
Could anyone tell me the problem in this code?
In the official document, it said At the moment test hooks run, the tested webpage is already loaded, so that you can use test actions and other test run API inside test hooks.
Thanks in advance.
It seems you missed the await keyword before the doLogin() call:
fixture`App > ${menuName}`
.page`${HOST}`
.beforeEach(async (t) => {
// Don't forget about await
await doLogin(t)
});
Due to the implementation details it's possible to call an async function without await in some cases, but it's better to not rely on this and always use await with async functions.
If you add the async keyword and it don't fix the test, feel free to create a bug report in the TestCafe repository and provide a complete example that can be run to reproduce the problem.