Scala.js basic tutorial SyntaxError: Unexpected token - scala.js

I am following this tutorial of scala.js
http://www.scala-js.org/tutorial/basic/
Right now my build.sbt file looks like
enablePlugins(ScalaJSPlugin)
name := "ScalaJSTut1"
version := "1.0"
scalaVersion := "2.12.4"
scalaJSUseMainModuleInitializer := true
libraryDependencies ++= Seq(
"be.doeraene" %%% "scalajs-jquery" % "0.9.1"
)
skip in packageJSDependencies := false
jsDependencies +=
"org.webjars" % "jquery" % "2.1.4" / "2.1.4/jquery.js"
jsEnv := new org.scalajs.jsenv.jsdomnodejs.JSDOMNodeJSEnv()
I also successfully executed
npm install jsdom
my index.html looks like
<!DOCTYPE html>
<html>
<head>
<meta CHARSET="UTF-8" />
<title>MY FIRST SCALA.JS APPLICATION</title>
</head>
<body>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" src="./target/scala-2.12/scalajstut1-fastopt.js"></script>
<script type="text/javascript" src="./target/scala-2.12/scalajstut1-jsdeps.js"></script>
<button id="click-me-button" type="button">
Click me!
</button>
</body>
</html>
and finally TutorialApp.scala
package tutorial.webapp
import org.scalajs.jquery.jQuery
import scala.scalajs.js.annotation.JSExportTopLevel
object TutorialApp {
def main(args: Array[String]) : Unit = {
jQuery(() => setupUI())
}
def appendPar(text: String) : Unit = {
jQuery("body").append(s"<p>$text</p>")
}
#JSExportTopLevel("addClickedMessage")
def addClickedMessage() : Unit = {
appendPar("You clicked the button")
}
def setupUI() : Unit = {
appendPar("Hello World")
jQuery("#click-me-button").click(() => addClickedMessage())
}
}
but now when I do sbt run I get an error
[error] /Users//IdeaProjects/ScalaJSTut1/node_modules/jsdom/lib/api.js:10
[error] const { URL } = require("whatwg-url");
[error] ^
[error]
[error] SyntaxError: Unexpected token {
[error] at exports.runInThisContext (vm.js:53:16)
[error] at Module._compile (module.js:374:25)
[error] at Object.Module._extensions..js (module.js:405:10)
[error] at Module.load (module.js:344:32)
[error] at Function.Module._load (module.js:301:12)
[error] at Module.require (module.js:354:17)
[error] at require (internal/module.js:12:17)
[error] at [stdin]:39:13
[error] at [stdin]:67:3
[error] at Object.exports.runInThisContext (vm.js:54:17)
org.scalajs.jsenv.ExternalJSEnv$NonZeroExitException: Node.js with JSDOM exited with code 1
at org.scalajs.jsenv.ExternalJSEnv$AbstractExtRunner.waitForVM(ExternalJSEnv.scala:119)
at org.scalajs.jsenv.ExternalJSEnv$ExtRunner.run(ExternalJSEnv.scala:168)
at org.scalajs.sbtplugin.ScalaJSPluginInternal$.org$scalajs$sbtplugin$ScalaJSPluginInternal$$jsRun(ScalaJSPluginInternal.scala:787)
at org.scalajs.sbtplugin.ScalaJSPluginInternal$$anonfun$76$$anonfun$apply$51$$anonfun$apply$52.apply(ScalaJSPluginInternal.scala:939)
at org.scalajs.sbtplugin.ScalaJSPluginInternal$$anonfun$76$$anonfun$apply$51$$anonfun$apply$52.apply(ScalaJSPluginInternal.scala:933)
at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
[trace] Stack trace suppressed: run last compile:run for the full output.
[error] (compile:run) org.scalajs.jsenv.ExternalJSEnv$NonZeroExitException: Node.js with JSDOM exited with code 1
[error] Total time: 2 s, completed Nov 5, 2017 11:16:58 PM
~/IdeaProjects/ScalaJSTut1 >
when I do nom --version on my computer I see
npm --version
3.3.12

I was able to resolve the issue. The problem is that my npm version was outdated.
I did the following
brew install nvm
nvm install node
Now my npm --version shows
~/IdeaProjects/ScalaJSTut1 > npm --version
5.5.1
This resolved the problem.

Related

sbt,publishLocal and publish,Undefined resolver

I want to push my artifacts to local ivy repository and remote repository in order to use them as dependencies in other projects.
But none of them success.
My SparkBuild.scala:
resolvers := Seq(
// Google Mirror of Maven Central, placed first so that it's used instead of flaky Maven Central.
// See https://storage-download.googleapis.com/maven-central/index.html for more info.
"gcs-maven-central-mirror" at "https://maven-central.storage-download.googleapis.com/maven2/",
DefaultMavenRepository,
Resolver.mavenLocal,
Resolver.file("ivyLocal", file(Path.userHome.absolutePath + "/.ivy2/local"))(Resolver.ivyStylePatterns)
),
externalResolvers := resolvers.value,
otherResolvers := SbtPomKeys.mvnLocalRepository(dotM2 => Seq(Resolver.file("dotM2", dotM2))).value,
publishLocalConfiguration in MavenCompile := PublishConfiguration()
.withResolverName("dotM2")
.withArtifacts(packagedArtifacts.value.toVector)
.withLogging(ivyLoggingLevel.value),
publishLocalConfiguration in SbtCompile := PublishConfiguration()
.withResolverName("ivyLocal")
.withArtifacts(packagedArtifacts.value.toVector)
.withLogging(ivyLoggingLevel.value),
publishMavenStyle in MavenCompile := true,
publishMavenStyle in SbtCompile := false,
publishLocal in MavenCompile := publishTask(publishLocalConfiguration in MavenCompile).value,
publishLocal in SbtCompile := publishTask(publishLocalConfiguration in SbtCompile).value,
publishLocal := Seq(publishLocal in MavenCompile, publishLocal in SbtCompile).dependOn.value,
publishTo := {
val nexus = "http://maven.baidu-int.com/nexus/content/repositories/"
if (isSnapshot.value)
Some("snapshots" at nexus + "Baidu_Local_Snapshots")
else
Some("releases" at nexus + "Baidu_Local")
},
Run publishLocal task:
[error] (sql / publish) Undefined resolver 'snapshots'
[error] (tags / publish) Undefined resolver 'snapshots'
[error] (sql-kafka-0-10 / publish) Undefined resolver 'snapshots'
[error] java.lang.RuntimeException: Undefined resolver 'snapshots'
[error] at scala.sys.package$.error(package.scala:30)
[error] at sbt.internal.librarymanagement.IvyActions$.$anonfun$publish$1(IvyActions.scala:136)
[error] at sbt.internal.librarymanagement.IvyActions$.$anonfun$publish$1$adapted(IvyActions.scala:133)
I can run compile, UT, package successfully, but just cannot publish.
What's wrong with it?

ScalaJS Uncaught TypeError: (0 , $m_Lorg_scalajs_jquery_package$(...).jQuery$1) is not a function

I am reading this tutorial for ScalaJS
https://www.scala-js.org/tutorial/basic/
As you can see in my build.sbt, that I have included the reference to the jQuery library
enablePlugins(ScalaJSPlugin)
// This is an application with a main method
scalaJSUseMainModuleInitializer := true
name := "ScalaJSTest"
version := "1.0"
scalaVersion := "2.12.1"
libraryDependencies ++= Seq(
"org.scala-js" %%% "scalajs-dom" % "0.9.1",
"be.doeraene" %%% "scalajs-jquery" % "0.9.1"
)
jsDependencies += RuntimeDOM
skip in packageJSDependencies := false
jsDependencies +=
"org.webjars" % "jquery" % "2.1.4" / "2.1.4/jquery.js"
I have also included the jsDeps and the jquery library in my HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The Scala.js Tutorial</title>
</head>
<body>
<!-- Include Scala.js compiled code -->
<script type="text/javascript" src="./target/scala-2.12/scalajstest-fastopt.js"></script>
<script type="text/javascript" src="./target/scala-2.12/scalajstest-jsdeps.js"></script>
</body>
</html>
I also did
npm install jsdom
This is my scalajs code
import scala.scalajs.js.JSApp
import org.scalajs.dom
import dom.document
import org.scalajs.jquery.jQuery
import scala.scalajs.js.annotation.JSExportTopLevel
object ScalaJsTest extends JSApp {
def main() : Unit = {
jQuery(() => setupUI())
}
def appendPar(node: dom.Node, text: String) : Unit = {
jQuery("body").append(s"<p>$text</p>")
}
#JSExportTopLevel("addClickedMessage")
def addClickedMessage(): Unit = {
appendPar(document.body, "You clicked the button!")
}
def setupUI(): Unit = {
jQuery("#click-me-button").click(() => addClickedMessage())
jQuery("body").append("<p>Hello World</p>")
}
}
But still my code gets the following error
Uncaught TypeError: (0 , $m_Lorg_scalajs_jquery_package$(...).jQuery$1) is not a function
at $c_LScalaJsTest$.appendPar__Lorg_scalajs_dom_raw_Node__T__V (scalajstest-fastopt.js:2341)
at $c_LScalaJsTest$.main__V (scalajstest-fastopt.js:2332)
at scalajstest-fastopt.js:6848
at scalajstest-fastopt.js:6849
You need to include the script tag with jsdeps before the one for fastopt.js. Otherwise, by the time your main method runs, jQuery has not been loaded yet.

Using scala-js-env-selenium for crossbrowser testing

I am using https://github.com/scala-js/scala-js-env-selenium for in-browser testing, so far tests are running fine in local browser. Now i want to run my tests in remote browsers (https://app.crossbrowsertesting.com)
I created new CrossBrowser
import org.openqa.selenium.remote.{DesiredCapabilities, RemoteWebDriver}
import org.scalajs.jsenv.selenium.{BrowserDriver, SeleniumBrowser}
import java.net.URL
object CrossBrowser {
def apply(): CrossBrowser = new CrossBrowser
val username = "email"
// Your username
val authkey = "xxxxxxxxxx" // Your authkey
}
class CrossBrowser private() extends SeleniumBrowser {
def name: String = "RemoteBrowser"
def newDriver: BrowserDriver = new CrossDriver
private class CrossDriver extends BrowserDriver {
protected def newDriver(): RemoteWebDriver = {
val caps = new DesiredCapabilities()
caps.setCapability("name", "Selenium Test Example")
caps.setCapability("build", "1.0")
caps.setCapability("browser_api_name", "IE10")
caps.setCapability("os_api_name", "Win7x64-C2")
caps.setCapability("screen_resolution", "1024x768")
caps.setCapability("record_video", "true")
caps.setCapability("record_network", "true")
new RemoteWebDriver(new URL("http://" + CrossBrowser.username + ":" + CrossBrowser.authkey + "#hub.crossbrowsertesting.com:80/wd/hub"), caps)
}
}
}
and updated build settings
jsEnv := new org.scalajs.jsenv.selenium.SeleniumJSEnv(CrossBrowser()),
jsEnv in Test := new org.scalajs.jsenv.selenium.SeleniumJSEnv(CrossBrowser())
when i ran test command i got following output
[trace] Stack trace suppressed: run last client/test:loadedTestFrameworks for the full output.
[error] (client/test:loadedTestFrameworks) org.openqa.selenium.WebDriverException: [fc92901a-f56a-4e4b-9d75-953402cbfe35] Test has timed out after 199 seconds
[error] Command duration or timeout: 199.20 seconds
[error] Build info: version: '2.53.0', revision: '35ae25b1534ae328c771e0856c93e187490ca824', time: '2016-03-15 10:43:46'
[error] System info: host: 'Chandras-MacBook-Pro.local', ip: 'xx.xx.xxx.x', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.3', java.version: '1.8.0_25'
[error] Driver info: org.openqa.selenium.remote.RemoteWebDriver
[error] Capabilities [{browserAttachTimeout=0, enablePersistentHover=true, ie.forceCreateProcessApi=false, pageLoadStrategy=normal, ie.usePerProcessProxy=false, ignoreZoomSetting=false, handlesAlerts=true, version=10, platform=WINDOWS, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, webdriver.remote.sessionid=fc92901a-f56a-4e4b-9d75-953402cbfe35, requireWindowFocus=false, browserName=internet explorer, initialBrowserUrl=http://localhost:33793/, takesScreenshot=true, javascriptEnabled=true, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=dismiss}]
[error] Session ID: fc92901a-f56a-4e4b-9d75-953402cbfe35
Reason for time out is , test-runner tried to load file:/var/folders/n0/c0fyqlqx0gg15mv4t5mchgj80000gn/T/1464125278337-0/scalajsRun.html on remote machine which doesn't exist.
is it possible to do this kind of testing ..?(copy files to some server and load that url ..)
Selenium will need access to your files if you are running local tests. That's usually done via proxies. There seems to be support for local testing though (https://crossbrowsertesting.com/local-testing), you could try to contact them to set this up.

ScalaTest DeferredAbortedSuite error when running simple tests.

My original code had a lot more going on, which distracted me from the true cause of the problem.
This captures the essential problem.
import org.scalatest.AsyncFlatSpec
import scala.concurrent.Future
class AsyncFlatSpecSpec extends AsyncFlatSpec
{
it should "parse an XML file" in {
// ... Parsing ...
Future.successful(succeed)
}
it should "parse an XML file" in {
// ... Serializing ...
Future.successful(succeed)
}
}
This produced these errors:
[info] DeferredAbortedSuite:
[error] Uncaught exception when running AsyncFlatSpecSpec: java.lang.ArrayIndexOutOfBoundsException: 17
[trace] Stack trace suppressed: run last test:testOnly for the full output.
There is no array access happening anywhere in my code. What's going on?
Running "last test:testOnly" wasn't much help:
[info] DeferredAbortedSuite:
[error] Uncaught exception when running AsyncFlatSpecSpec: java.lang.ArrayIndexOutOfBoundsException: 17
sbt.ForkMain$ForkError: java.lang.ArrayIndexOutOfBoundsException: 17
at org.scalatest.exceptions.StackDepth$class.stackTraceElement(StackDepth.scala:63)
at org.scalatest.exceptions.StackDepth$class.failedCodeFileName(StackDepth.scala:77)
at org.scalatest.exceptions.StackDepthException.failedCodeFileName(StackDepthException.scala:36)
at org.scalatest.exceptions.StackDepth$class.failedCodeFileNameAndLineNumberString(StackDepth.scala:59)
at org.scalatest.exceptions.StackDepthException.failedCodeFileNameAndLineNumberString(StackDepthException.scala:36)
at org.scalatest.tools.StringReporter$.withPossibleLineNumber(StringReporter.scala:442)
at org.scalatest.tools.StringReporter$.stringsToPrintOnError(StringReporter.scala:916)
at org.scalatest.tools.StringReporter$.fragmentsForEvent(StringReporter.scala:747)
at org.scalatest.tools.Framework$SbtLogInfoReporter.apply(Framework.scala:622)
at org.scalatest.tools.FilterReporter.apply(FilterReporter.scala:41)
at org.scalatest.tools.SbtDispatchReporter$$anonfun$apply$1.apply(SbtDispatchReporter.scala:23)
at org.scalatest.tools.SbtDispatchReporter$$anonfun$apply$1.apply(SbtDispatchReporter.scala:23)
at scala.collection.Iterator$class.foreach(Iterator.scala:893)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
at org.scalatest.tools.SbtDispatchReporter.apply(SbtDispatchReporter.scala:23)
at org.scalatest.tools.Framework$SbtReporter.apply(Framework.scala:1119)
at org.scalatest.tools.Framework.org$scalatest$tools$Framework$$runSuite(Framework.scala:387)
at org.scalatest.tools.Framework$ScalaTestTask.execute(Framework.scala:506)
at sbt.ForkMain$Run$2.call(ForkMain.java:296)
at sbt.ForkMain$Run$2.call(ForkMain.java:286)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Confused, I retreated to the non-Async version, to see if that fared any
better.
import org.scalatest.FlatSpec
class FlatSpecSpec extends FlatSpec {
it should "parse an XML file" in {
// ... Parsing ...
succeed
}
it should "parse an XML file" in {
// ... Serializing ...
succeed
}
}
It produced this different, but still cryptic error message:
[info] DeferredAbortedSuite:
[info] Exception encountered when attempting to run a suite with class name: org.scalatest.DeferredAbortedSuite *** ABORTED *** (20 milliseconds)
[info] Exception encountered when attempting to run a suite with class name: org.scalatest.DeferredAbortedSuite (AsyncFlatSpecSpec.scala:32)
[info] ScalaTest
For completeness, here are the related portions of my build.sbt:
scalaVersion := "2.11.8"
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.0-M15" % "test"
libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.0-M15"
This was ultimately a trivial mistake on my part, but I wanted to post this for the sake of anyone else Googling these errors.
As many readers probably noticed while going through the examples, the problem was that I had copy/pasted the same test description.
This allows the code to compile, but will fail at runtime with errors that
don't identify the description as the culprit.
Stupid error on my part, but it would be nice if the compiler reported it in a more helpful way.

java.io.IOException: Unable to download JavaScript from 'http://localhost:19001/assets/javascripts/jquery-1.9.0.min.js' (status 404)

I know many will say this was answered on another thread, but I haven't found an answer to this problem. Either the thread is hijacked, or the fixes don't work.
I'm using IntelliJ IDEA 2016.1
Build #IU-145.258, built on March 17, 2016
My Project SDK is 1.8.0_73, Scala version is 2.11, and Play 2 version is 2.5.0.
I'm running my tests from the IDE by right clicking on the test folder of my project and click on Debug 'All Tests'. They all pass, but I get the following error.
java.io.IOException: Unable to download JavaScript from 'http://localhost:19001/assets/javascripts/jquery-1.9.0.min.js' (status 404).
The IOException occurs in IntegrationSpec.scala. Can anyone help resolve this issue?
here are the files of my project.
Thanking you in advance
Francis
build.sbt
name := "test"
version := "1.0"
lazy val `test` = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.11.7"
libraryDependencies ++= Seq( jdbc , cache , ws , specs2 % Test )
unmanagedResourceDirectories in Test <+= baseDirectory ( _ /"target/web/public/test" )
resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases"
routes
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
build.properties
sbt.version=0.13.5
plugins.sbt
logLevel := Level.Warn
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.0")
Application.scala
package controllers
import play.api._
import play.api.mvc._
class Application extends Controller {
def index = Action {
Ok(views.html.index("Your new application is ready."))
}
}
main.scala.html
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script src="#routes.Assets.at("javascripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
</head>
<body>
#content
</body>
</html>
IntegrationSpec.scala
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.test._
import play.api.test.Helpers._
/**
* add your integration spec here.
* An integration test will fire up a whole play application in a real (or headless) browser
*/
#RunWith(classOf[JUnitRunner])
class IntegrationSpec extends Specification {
"Application" should {
"work from within a browser" in new WithBrowser {
browser.goTo("http://localhost:" + port)
browser.pageSource must contain("Your new application is ready.")
}
}
}