I am getting
Jasmine spec timed out. Resetting the WebDriver Control Flow.
I have also used fakesyn before but getting same error message as above.
Please help me
This is my specs:
describe('CW Login Page', function() {
var username;
var password;
var login;
beforeEach(() => {
browser.waitForAngularEnabled(false);
browser.get('http://www.testing.com/');
console.log('after link await');
});
it('should find the element and send the parameters', fakeAsync(() => {
setTimeout(function() {
value=0;
console.log('Inside it function');
username = element(by.id('userIDInput'));
password= element(by.id('passwordInput'));
login= element(by.id('login'));
console.log('After await');
username.sendKeys('abc');
password.sendKeys('abc');
login.click();
console.log("After it function");
},5000);
tick(5000);
}));
`beforeEach`(() => {
console.log('\r\n ---=== TESTS FINISHED!!! ===--- \r\n');
});
});
This is my config:
exports.config = {
allScriptsTimeout: 50000,
getPageTimeout:40000,
framework:'jasmine2',
/*seleniumAddress: 'http://localhost:4723/wd/hub', // Ignored if directConnect is true
specs: ['loginpage.js'],*/
seleniumAddress: 'https://hub.testingbot.com/wd/hub',
specs: ['./src/loginpage_fakeasync.e2e-specs.js'],
seleniumArgs: ['--dev-server-target'], // '--dev-server-target' ],
directConnect: false, //Change this to true for your local testing
multiCapabilities: [{ // in 1 chrome run the 10 specs sequentially
browserName: 'chrome',
platform: 'Android',
version: '7.1',
platformName: 'Android',
deviceName: 'Pixel 2',
client_key: "abc",
client_secret: "xyz"
}],
jasmineNodeOpts: {
onComplete: null, //jasmine framework details
isVerbose: false,
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 40000,
print: function() {}
I expect to open the webpage and login using the automation script. If someone can figure out the error it would be a great help
I am getting
Jasmine spec timed out. Resetting the WebDriver Control Flow.
I have also used fakesyn before but getting same error message as above.
Please help me
The control flow should keep everything running in sync so the fakeAsync & setTimeout should not be required. If your framework is not too large then you should consider disabling the control flow and using the async/await style of handling promises.
I doubt this will solve your issue but can you try the below code and post the results.
describe('CW Login Page', function () {
var username;
var password;
var login;
beforeEach(() => {
browser.waitForAngularEnabled(false);
browser.get('http://www.testing.com/');
console.log('after link await');
});
it('should find the element and send the parameters', () => {
value = 0;
console.log('Inside it function');
username = element(by.id('userIDInput'));
password = element(by.id('passwordInput'));
login = element(by.id('login'));
console.log('After await');
username.sendKeys('abc');
password.sendKeys('abc');
login.click();
console.log("After it function");
})
afterEach(() => {
console.log('\r\n ---=== TESTS FINISHED!!! ===--- \r\n');
}
});
Related
I am creating a project where I need to take a user input - pass it through a function and return the new value to the user - seems simple enough. I am new to async functions and have read everything I possibly can, and can't works out if there's a more fundamental issue I am missing. I will show the basic code, and then what I wish to achieve. I believe the issue, is that I am returning back the status of the function rather than the value, but just can't work it out.
Basic Code:
ipcMain.on('gpt3', (event, args) => {
async function gpt3(args) {
generateResponse('james', 'hello world'); // Takes a user's name & input and recieves a response from a python file.
event.reply('textRecieve', 'hello world'); // Sends 'Hello World' to the user (ipcRenderer 'textRecieve')
}
gpt3(args);
})
async function generateResponse(name, text) {
let testshell = new PythonShell('./python/text_echo.py', { mode: 'text', args: [name, text]});
let content = "";
try {
testshell.on('message', function (message) {
console.log(message); // prints the output from the python file 'Python File: james Text: hello world'
return message; // attempting to return the 'Message' from the python file
});
} catch (error) {
console.log("You've f*cked it somewhere my friend");
console.log(error);
}
}
Python Script:
import sys
name = sys.argv[1]
text = sys.argv[2]
print(f'Python File: {name} Text: {text}')
sys.stdout.flush()
Returns: (as expected)
> Executing task: npm run start <
> electron-quick-start#1.0.0 start
> electron .
Python File: james Text: hello world
What I'd Like it to do:
ipcMain.on('gpt3', (event, args) => {
async function gpt3(args) {
message = generateResponse('james', 'hello world'); // Takes a user's name & input and recieves a response from a python file, retunring the message to the 'message' variable.
console.log(message);
event.reply('textRecieve', 'message would send here'); // Sends the 'Message' to the user (ipcRenderer 'textRecieve')
}
gpt3(args);
})
async function generateResponse(name, text) {
let testshell = new PythonShell('./python/text_echo.py', { mode: 'text', args: [name, text]});
let content = ""
try {
testshell.on('message', function (message) {
console.log(message); // prints the output from the python file 'Python File: james Text: hello world'
return message; // attempting to return the 'Message' from the python file
});
} catch (error) {
console.log("You've f*cked it somewhere my friend")
console.log(error)
}
return content; // content needs to be message instead due to async nature it returns empty string
}
Returns:
> Executing task: npm run start <
> electron-quick-start#1.0.0 start
> electron .
Promise { '' }
Python File: james Text: hello world
TLDR; I would like to take the 'message' generated through 'generateResponse()' and pass it through to my 'event.reply()'. Instead, I am receiving what I believe to be the status of the Promise. Any help would be greatly appreciated. Thanks
You should resolve the promise first.
ipcMain.on('gpt3', (event, args) => {
async function gpt3(args) {
const message = await generateResponse('james', 'hello world');
console.log(message);
event.reply('textRecieve', 'message would send here'); // Sends the 'Message' to the user (ipcRenderer 'textRecieve')
}
gpt3(args);
})
async function generateResponse(name, text) {
let testshell = new PythonShell('./python/text_echo.py', { mode: 'text', args: [name, text]});
let content = ""
try {
testshell.on('message', function (message) {
console.log(message); // prints the output from the python file 'Python File: james Text: hello world'
content = message;
});
} catch (error) {
console.log("You've f*cked it somewhere my friend")
console.log(error)
}
return content; // content needs to be message instead due to async nature it returns empty string
}
Okay, so there were a few problems here... but the main was node.js 'non-ability' to pass variables around when 'asynchronous'. with node.js being new to me, I can't lie and say I was confused. Hopefully, the following link to a great workaround/method and my working code will be able to help someone:
https://stackoverflow.com/a/23667087/10246221
Code:
ipcMain - nested within app.whenReady().
ipcMain.on('gpt3', (event, input) => {
gpt3Async(event, input, function(result) {
event.reply('textRecieve', result);
console.log('gpt3Async: '+ result);
})
})
Code:
Generic 'nested' Function - free-floating around 'main.js' or 'index.js'.
function gpt3Async(event, input, callback) {
console.log('input: ' + input)
let testshell = new PythonShell('./python/text_echo.py', { mode: 'text', args: ['elliott' ,input]});
testshell.on('message', function (message) {
callback(message);
});
}
Code: Python Script 'text_echo.py' - in my case within a 'python' subdirectory.
import sys
name = sys.argv[1]
text = sys.argv[2]
print(f'Python File: {name} Text: {text}')
#sys.stdout.flush()
sys.stdout.flush()
For anyone working on a project where you need input and output for python scripts, this will help you out. also make sure you turn on the following:
webPreferences: {
//preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
sandbox: false,
},
BUT!, please be aware of the security implications this will have on your code, More info is available here: https://stackoverflow.com/a/57507392 & https://electronjs.org/docs/tutorial/security#3-enable-context-isolation-for-remote-content & much more so do some reading if this is an important project...
Okay, An explainer, or at least something that blew my mind as a beginner... . The way I finally understood it was through the example link:
https://stackoverflow.com/a/23667087/10246221
for some reason, it hadn't clicked with me that functions could be nested within functions like this, all in one line. For someone who is used to JS or node.js this may seem fundamental, but seeing as this is a first-time project to me, and maybe others - if still using python code. Hopefully, this may help!
ipcMain.on('gpt3', (event, input) => { gpt3Async(event, input, function(result) { event.reply('textRecieve', result); console.log('gpt3Async: '+ result);})})
I'm writing tests (with Jest and React Testing Library) for a form React component. I have a method that runs on form submit:
const onSubmit = (data) => {
// ...
setIsPopupActive(true);
// ...
};
and useEffect that runs after isPopupActive change, so also on submit:
useEffect(() => {
if (isPopupActive) {
setTimeout(() => {
setIsPopupActive(false);
}, 3000);
}
}, [isPopupActive]);
In the test, I want to check, whether the popup disappears after 3 seconds. So here's my test:
it('Closes popup after 3 seconds', async () => {
const nameInput = screen.getByPlaceholderText('Imię');
const emailInput = screen.getByPlaceholderText('Email');
const messageInput = screen.getByPlaceholderText('Wiadomość');
const submitButton = screen.getByText('Wyślij');
jest.useFakeTimers();
fireEvent.change(nameInput, { target: { value: 'Test name' } });
fireEvent.change(emailInput, { target: { value: 'test#test.com' } });
fireEvent.change(messageInput, { target: { value: 'Test message' } });
fireEvent.click(submitButton);
const popup = await waitFor(() =>
screen.getByText(/Wiadomość została wysłana/)
);
await waitFor(() => {
expect(popup).not.toBeInTheDocument(); // this passes
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 3000);
});
});
However, I'm getting the error:
expect(received).toHaveBeenCalledTimes(expected)
Matcher error: received value must be a mock or spy function
Received has type: function
Received has value: [Function setTimeout]
What am I doing wrong?
Jest 27 has breaking changes for fakeTimers. It seems Jest contributors doesn't update documentation on time. This comment on Github issues confirms it. Moreover, here related PR.
Well, you can solve your problem by two ways.
Configure Jest to use legacy fake timers. In jest.config.js you can add line (but it not works for me):
module.exports = {
// many of lines omited
timers: 'legacy'
};
Configure legacy fake timers for individually test suite, or even test:
jest.useFakeTimers('legacy');
describe('My awesome logic', () => {
// blah blah blah
});
It's preferably to use new syntax based on #sinonjs/fake-timers. But I can't find working example for Jest, so I'll update this answer as soon as possible.
The below approach worked
beforeEach(() => {
jest.spyOn(global, 'setTimeout');
});
afterEach(() => {
global.setTimeout.mockRestore();
});
it('Test if SetTimeout is been called', {
global.setTimeout.mockImplementation((callback) => callback());
expect(global.setTimeout).toBeCalledWith(expect.any(Function), 7500);
})
In your case setTimeout is not a mock or spy, rather, it's a real function. To make it a spy, use const timeoutSpy = jest.spyOn(window, 'setTimeout'). And use timeoutSpy in the assertion.
You could also test not the fact of calling the setTimeout function, but assert that setIsPopupActive was called once, and with false. For this you might need to do jest.runOnlyPendingTimers() or jest.runAllTimers()
Tried react-native-background-fetch and react-native-background-job both libraries does not run the code when app is closed, followed the documentation clearly
react-native-background-fetch job runs when custom event created using
when app is in foreground
adb shell cmd jobscheduler run -f com.bg_fetch 999
, also periodic event is not triggered after 15 min(as given in config)
For react-native-background-job job does not run even in background
Tested on android-9
componentDidMount() {
// Configure it.
BackgroundFetch.configure({
minimumFetchInterval: 15, // <-- minutes (15 is minimum allowed)
// Android options
stopOnTerminate: false,
startOnBoot: true,
requiredNetworkType: BackgroundFetch.NETWORK_TYPE_ANY, // Default
requiresCharging: false, // Default
requiresDeviceIdle: false, // Default
requiresBatteryNotLow: false, // Default
requiresStorageNotLow: false, // Default
enableHeadless:true,
}, async() => {
console.log('[BackgroundFetch HeadlessTask] start');
let response = await fetch('http://431c21b5.ngrok.io/');
let responseJson = await response.json();
console.log('[BackgroundFetch HeadlessTask] response: ', responseJson);
BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA);
}, (error) => {
console.log("[js] RNBackgroundFetch failed to start");
});
// Optional: Query the authorization status.
BackgroundFetch.status((status) => {
switch(status) {
case BackgroundFetch.STATUS_RESTRICTED:
console.log("BackgroundFetch restricted");
break;
case BackgroundFetch.STATUS_DENIED:
console.log("BackgroundFetch denied");
break;
case BackgroundFetch.STATUS_AVAILABLE:
console.log("BackgroundFetch is enabled");
break;
}
});
}
Job is supposed to run when app is in background or closed,
Headless job is getting killed after i close the app,
you need to put inside your index.js file your headlessTask
https://github.com/transistorsoft/react-native-background-fetch#config-boolean-enableheadless-false
I want to create a simple test with Seleinium and Cucumber to login to my webapp and then verify that all is as it should be on the main page. All three tests immediately return true even before the page has been fetched, but the When step fails to find the input element because it begins before the get request has been completed. I'm new to this framework so I could be doing everything completely wrong.
const capabilities = {
browserName: 'IE',
browser_version: '11.0',
os: 'Windows',
os_version: '10',
resolution: '1024x768',
'browserstack.user': 'henry',
'browserstack.key': 'pass',
name: 'Bstack-[Node] Sample Test'
};
const driver = new webdriver.Builder()
.usingServer('http://hub-cloud.browserstack.com/wd/hub')
.withCapabilities(capabilities)
.build();
Given('The login page loads', () => {
driver.get('https://example.com/').then(() => {
driver.getTitle().then((title) => {
expect(title).to.eql('My webapp');
});
});
});
When('I login', () => {
driver.findElement(webdriver.By.name('username')).sendKeys('henry#example.com');
});
Then('I should see the dashboard', () => {
});
Feature: Login
Login to the Petasense webapp
Scenario: Scenario name
Given The login page loads
When I login
Then I should see the dashboard
Please use wait before performing any action. For e.g
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.or(
ExpectedConditions.visibilityOfElementLocated(By.id("id1")),
ExpectedConditions.visibilityOfElementLocated(By.id("id2"))
));
Or use sleep before next step. e.g
Thread.sleep
I am trying to create a script for email verification. I mean when we create an account on the site, then a verification mail will come to the given mail address and then we have to go to that mail and verify it(clicking on the link/or fetching the code). I tried this solution. But I have got stuck on the specific error.
This is code which I am trying.
describe("Sample test case", function () {
function getLastEmail() {
let deferred = protractor.promise.defer();
console.log("Waiting for an email...");
mailListener.on("mail", function(mail){
deferred.fulfill(mail);
});
return deferred.promise;
}
beforeAll(function () {
browser.waitForAngularEnabled(false);
browser.get("https://mail.google.com/mail/");
isAngularSite(false);
browser.sleep(3000);
});
it("should login with a registration code sent to an email", function () {
element(by.id("username")).sendKeys("MyemailID");
element(by.id("password")).sendKeys("mypassword");
element(by.id("loginButton")).click();
browser.controlFlow().await(getLastEmail()).then(function (email) {
expect(email.subject).toEqual("BillPledge Email Verification");
expect(email.headers.to).toEqual("support#billpledge.com");
// extract registration code from the email message
let pattern = /Registration code is: (\w+)/g;
let regCode = pattern.exec(email.text)[1];
console.log(regCode);
});
});
});
and this is my conf file.
// An example configuration file.
exports.config = {
// The address of a running selenium server.
// seleniumAddress: 'http://localhost:4444/wd/hub',
// if we are using protractor's webdriver-manager locally, you cannot use selenium Address
// If the webdriver-manager needs to start a local server, you can use
selenium: 'http://localhost:4445/wd/hub',
seleniumPort: 4445, // Port matches the port above
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
// Spec patterns are relative to the current working directly when
// protractor is called.
specs: ['./e2eTest/GmailTest.js'],
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 300000
},
allScriptsTimeout: 200000,
onPrepare: function () {
global.isAngularSite = function (flag) {
browser.ignoreSynchronization = !flag;
};
browser.driver.manage().window().maximize();
//To generate the report.
let HtmlReporter = require('protractor-beautiful-reporter');
jasmine.getEnv().addReporter(new HtmlReporter({
baseDirectory: 'Results/Report'
}).getJasmine2Reporter());
let reporter = new HtmlReporter({
baseDirectory: 'Results/Report'
});
let path = require('path');
new HtmlReporter({
baseDirectory: 'Results/Report'
, preserveDirectory: false
, cssOverrideFile: 'css/style.css'
, takeScreenShotsForSkippedSpecs: true
, screenshotsSubfolder: 'images'
, jsonsSubfolder: 'jsons'
, takeScreenShotsOnlyForFailedSpecs: false
, gatherBrowserLogs: true
, pathBuilder: function pathBuilder(spec, descriptions, results, capabilities) {
// Return '<browser>/<specname>' as path for screenshots:
// Example: 'firefox/list-should work'.
return path.join(capabilities.caps_.browser, descriptions.join('-'));
}
, metaDataBuilder: function metaDataBuilder(spec, descriptions, results, capabilities) {
// Return the description of the spec and if it has passed or not:
return {
description: descriptions.join(' ')
, passed: results.passed()
};
}
});
let MailListener = require("mail-listener2");
// here goes your email connection configuration
let mailListener = new MailListener({
username: "myemailid",
password: "mypassword",
host: "imap.gmail.com",
port: 993, // imap port
tls: true,
tlsOptions: {rejectUnauthorized: false},
mailbox: "INBOX", // mailbox to monitor
searchFilter: ["UNSEEN", "FLAGGED"], // the search filter being used after an IDLE notification has been retrieved
markSeen: true, // all fetched email willbe marked as seen and not fetched next time
fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`,
mailParserOptions: {streamAttachments: true}, // options to be passed to mailParser lib.
attachments: true, // download attachments as they are encountered to the project directory
attachmentOptions: {directory: "attachments/"} // specify a download directory for attachments
});
mailListener.start();
mailListener.on("server:connected", function () {
console.log("Mail listener initialized");
});
global.mailListener = mailListener;
},
onCleanUp: function () {
mailListener.stop();
},
};
But while executing the script I am getting following error. The error is:
Error: Please log in via your web browser:
https://support.google.com/mail/accounts/answer/78754 (Failure)
and
Failed: browser.controlFlow(...).await is not a function
I know I am doing some mistake but I am not able to figure out. So can anyone can help me in pointing out and solve it, not solve but at least some suggestion which can help in running this script perfectly.
Thanks
Try to use browser.wait(getLastEmail) instead of browser.controlFlow().await(getLastEmail()