Unable to execute JavaScript when set current date

Hello everyone,

I try to set a current date in the text field without clicking the date picker icon, but I encountered an error Unable to execute javascript. Can someone who help me please. thanks!

2022-12-23 12:23:56.337 ERROR c.k.k.core.keyword.internal.KeywordMain  - ❌ Unable to execute JavaScript. (Root cause: com.kms.katalon.core.exception.StepFailedException: Unable to execute JavaScript.
	at com.kms.katalon.core.webui.keyword.internal.WebUIKeywordMain.stepFailed(WebUIKeywordMain.groovy:64)
	at com.kms.katalon.core.webui.keyword.internal.WebUIKeywordMain.runKeyword(WebUIKeywordMain.groovy:26)
	at com.kms.katalon.core.webui.keyword.builtin.ExecuteJavaScriptKeyword.executeJavascript(ExecuteJavascriptKeyword.groovy:42)
	at com.kms.katalon.core.webui.keyword.builtin.ExecuteJavaScriptKeyword.execute(ExecuteJavascriptKeyword.groovy:37)
	at com.kms.katalon.core.keyword.internal.KeywordExecutor.executeKeywordForPlatform(KeywordExecutor.groovy:74)
	at com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords.executeJavaScript(WebUiBuiltInKeywords.groovy:4873)
	at com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords$executeJavaScript$6.call(Unknown Source)
	at commercial.commercialOrder(commercial.groovy:83)
	at cucumber.runtime.Utils$1.call(Utils.java:26)
	at cucumber.runtime.Timeout.timeout(Timeout.java:16)
	at cucumber.runtime.Utils.invoke(Utils.java:20)
	at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:48)
	at cucumber.runtime.PickleStepDefinitionMatch.runStep(PickleStepDefinitionMatch.java:50)
	at cucumber.runner.TestStep.executeStep(TestStep.java:68)
	at cucumber.runner.TestStep.run(TestStep.java:50)
	at cucumber.runner.PickleStepTestStep.run(PickleStepTestStep.java:53)
	at cucumber.runner.TestCase.run(TestCase.java:47)
	at cucumber.runner.Runner.runPickle(Runner.java:44)
	at cucumber.runtime.Runtime.runFeature(Runtime.java:120)
	at cucumber.runtime.Runtime.run(Runtime.java:106)
	at cucumber.api.cli.Main.run(Main.java:35)
	at cucumber.api.cli.Main$run.call(Unknown Source)
	at com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords$_runFeatureFile_closure1.doCall(CucumberBuiltinKeywords.groovy:108)
	at com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords$_runFeatureFile_closure1.doCall(CucumberBuiltinKeywords.groovy)
	at com.kms.katalon.core.keyword.internal.KeywordMain.runKeyword(KeywordMain.groovy:74)
	at com.kms.katalon.core.keyword.internal.KeywordMain.runKeyword(KeywordMain.groovy:68)
	at com.kms.katalon.core.keyword.internal.KeywordMain$runKeyword.call(Unknown Source)
	at com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords.runFeatureFile(CucumberBuiltinKeywords.groovy:75)
	at com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords$runFeatureFile$0.callStatic(Unknown Source)
	at com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords.runFeatureFile(CucumberBuiltinKeywords.groovy:248)
	at com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords$runFeatureFile.call(Unknown Source)
	at WSVerification1671769377129.run(WSVerification1671769377129:2)
	at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
	at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
	at com.kms.katalon.core.main.WSVerificationExecutor.runScript(WSVerificationExecutor.java:180)
	at com.kms.katalon.core.main.WSVerificationExecutor.doExecute(WSVerificationExecutor.java:174)
	at com.kms.katalon.core.main.WSVerificationExecutor.processExecutionPhase(WSVerificationExecutor.java:157)
	at com.kms.katalon.core.main.WSVerificationExecutor.accessMainPhase(WSVerificationExecutor.java:149)
	at com.kms.katalon.core.main.WSVerificationExecutor.execute(WSVerificationExecutor.java:131)
	at com.kms.katalon.core.main.TestCaseMain.runFeatureFile(TestCaseMain.java:172)
	at com.kms.katalon.core.main.TestCaseMain$runFeatureFile$0.call(Unknown Source)
	at TempTempCase1671769373775.run(TempTempCase1671769373775.groovy:25)
Caused by: org.openqa.selenium.JavascriptException: javascript error: screenFormattedDate is not defined
  (Session info: chrome=108.0.5359.124)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'phlt-00038', ip: 'fe80:0:0:0:1cf1:4baf:11b1:450c%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.16', java.version: '1.8.0_275'
Driver info: com.kms.katalon.selenium.driver.CChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 108.0.5359.124, chrome: {chromedriverVersion: 107.0.5304.62 (1eec40d3a576..., userDataDir: /var/folders/11/pr4jwmlx0_g...}, goog:chromeOptions: {debuggerAddress: localhost:53306}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: MAC, platformName: MAC, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Session ID: f410fb85b913551348f7085d319f4ee1
	at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
	at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
	at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
	at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
	at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
	at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
	at com.kms.katalon.selenium.driver.CChromeDriver.execute(CChromeDriver.java:19)
	at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:489)
	at org.openqa.selenium.support.events.EventFiringWebDriver.lambda$new$1(EventFiringWebDriver.java:105)
	at com.sun.proxy.$Proxy18.executeScript(Unknown Source)
	at org.openqa.selenium.support.events.EventFiringWebDriver.executeScript(EventFiringWebDriver.java:229)
	at com.kms.katalon.core.webui.keyword.builtin.ExecuteJavaScriptKeyword$_executeJavascript_closure1.doCall(ExecuteJavascriptKeyword.groovy:48)
	at com.kms.katalon.core.webui.keyword.builtin.ExecuteJavaScriptKeyword$_executeJavascript_closure1.call(ExecuteJavascriptKeyword.groovy)
	at com.kms.katalon.core.webui.keyword.internal.WebUIKeywordMain.runKeyword(WebUIKeywordMain.groovy:20)
	... 40 more
)
2022-12-23 12:23:56.352 ERROR c.runtime.formatter.CucumberReporter     - ❌ Create Commercial Order FAILED.
Reason:
com.kms.katalon.core.exception.StepFailedException: Unable to execute JavaScript.
1 Like

Hello,

I already fix the error “Unable to execute JavaScript” now I am getting new error “Invalid element state” . Can anyone help me pls. thanks!

The screenshot you shared is not enough. It does not tell us on which statement in the Test Case caused the error “Invalid element state”.

Hi @kazurayam sorry, what do you mean on the statement? In the screenshot that I provided that is the script/code to set or input a date on the text field only and nothing else to do.

When you set the date in the textbox, does a Calendar GUI appear? If it does, and you are trying to “setText()” as well as javascript it, then you may be “butting heads” with yourself. Personally…

Date todaysDate = new Date();
def screenFormattedDate = todaysDate.format("MM/dd/yyyy");
WebUI.setText(findTestObject('Order/dateSigned'), screenFormattedDate)
WebUI.verifyElementAttributeValue(...

Curious, your setText() statement and your verifyElementAttributeValue() statement are working on different elements. Is this a copy and paste error?

Edit: Just a note that if a Calendar GUI does appear, what I do is click on a textarea, textbox or even a label that is outside the Calendar GUI which should make the GUI disappear. I don’t suggest clicking or setting text on any element that is underneath (overlaid by) the Calendar GUI until it does disappear.

1 Like

Forget my previous post, please. I was too much confused by the title of this post and your code.


+1 to @grylion54


@escalryan

Why do you want to execute JavaScript in browser? The following 2 lines in your code are just unnecessary, as @grylion54 pointed out.

WebElement element = WebUiCommonHelper.findWebElement(findTestObject('Order/dataSigned'),30)
WebUI.executeJavaScript("arguments[0].value= '${screenFormattedDate}':", Arrays.asList(element))

Using JavaScript is, almost always, a test-case-code-smell…

If your datepicker widget is anything like the ones in Zoho (it auto-populates with today’s date, and setting the text to different date either has no effect or appends to today’s date string), try this out:

public final class GeneralWebUIUtils { 
    public static final String VALUE = "value";

    public static String GetTextValue(TestObject to) {
        return WebUI.getAttribute(to, this.VALUE)
    }

    public static Keys GetCommandKey() {
        final String os = System.getProperty("os.name")

        if (os.toUpperCase().contains("WINDOWS"))
            return Keys.CONTROL;

        return Keys.COMMAND;
    }

    public static void ClearAndEnterText(TestObject to, String text) {
        WebUI.sendKeys(to,
                Keys.chord("${this.GetCommandKey().toString()}A"),
                FailureHandling.STOP_ON_FAILURE);

        WebUI.sendKeys(to, text, FailureHandling.STOP_ON_FAILURE);
    }

    public static void UpdateDateField(TestObject to, Date newDate) {
        this.WaitForTextFieldNonEmpty(to, 1, FailureHandling.CONTINUE_ON_FAILURE)

        if (newDate == null) {
            WebUI.clearText(to, FailureHandling.STOP_ON_FAILURE);
            return;
        }

        final String fieldTextValue = this.GetTextValue(to),
        newDateTextValue = SMDDateUtils.ToDateString(newDate);

        if ((!newDateTextValue.isEmpty()) && (!fieldTextValue.equals(newDateTextValue))) {
            this.ClearAndEnterText(to, newDateTextValue);

            KeywordUtil.logInfo("'${newDateTextValue}' written to the date field")
        }

        WebUI.sendKeys(to, Keys.TAB.toString());
        KeywordUtil.logInfo("After trying to write to the field, it has value '${this.GetTextValue(to)}'")
    }

    public static boolean WaitForElementCondition(Closure<Boolean> onCheckCondition, Closure onContinue, TestObject to, int timeOut, FailureHandling failureHandling = FailureHandling.STOP_ON_FAILURE) {
        final long startTime = System.currentTimeMillis()
        boolean isConditionSatisfied = false;
        while ((System.currentTimeMillis() < startTime + timeOut * 1000) && (!isConditionSatisfied)) {
            isConditionSatisfied = WebUI.waitForElementPresent(to, 1, failureHandling) && onCheckCondition(to);
            if (onContinue != null)
                onContinue(isConditionSatisfied, to);
        }
        if ((!isConditionSatisfied) && (failureHandling.equals(FailureHandling.STOP_ON_FAILURE))) {
            KeywordUtil.markFailedAndStop("Condition for TestObject '${to.getObjectId()}' not met after ${(System.currentTimeMillis() - startTime) / 1000} seconds");
        }
        return isConditionSatisfied;
    }

    public static boolean WaitForTextFieldNonEmpty(TestObject to, int timeOut, FailureHandling failureHandling = FailureHandling.STOP_ON_FAILURE) {
        return this.WaitForElementCondition({ TestObject testObj ->
            return (!this.GetTextValue(testObj).isEmpty());
        },
        null,
        to,
        timeOut,
        failureHandling);
    }
}

public final class SMDDateUtils { 
	// TODO: replace with the date format that you use in your project
	private static DateFormat DateFormat =  new SimpleDateFormat("MM-dd-yyyy");

	public static String ToDateString(Date date) {
		return this.DateFormat.format(date);
	}
}

Save that to two keywords: GeneralWebUIUtils and SMDDateUtils (feel free to replace the name prefix on that one :slight_smile: )

Then you can just be like:

GeneralWebUIUtils.UpdateDateField(findTestObject('Order/dataSigned'), todaysDate)

to update to todaysDate

and even

GeneralWebUIUtils.UpdateDateField(findTestObject('Order/dataSigned'), null)

to clear it! :slight_smile:

DISCLAIMER: those utils are pulled straight from my testing codebase.

1 Like

Hi @grylion54 @kazurayam @mwarren04011990 sorry for the late response, I already resolved my issue by fixing the xpath of my element thank you!