Skip to content

Commit

Permalink
Added TestErrorBoundary to test module, fixed #4
Browse files Browse the repository at this point in the history
  • Loading branch information
viktor-podzigun committed Nov 11, 2021
1 parent 6a97b60 commit 7e2c823
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
28 changes: 28 additions & 0 deletions test/src/main/scala/scommons/react/test/TestErrorBoundary.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package scommons.react.test

import scommons.react._

import scala.scalajs.js

object TestErrorBoundary extends ClassComponent[Unit] {

private case class TestErrorBoundaryState(error: Option[js.Object] = None)

protected def create(): ReactClass = createClass[TestErrorBoundaryState](
getInitialState = { _ =>
TestErrorBoundaryState()
},
componentDidCatch = { (self, error, _) =>
self.setState(TestErrorBoundaryState(Option(error)))
},
render = { self =>
self.state.error match {
case None => self.props.children
case Some(error) =>
<.div()(
s"$error"
)
}
}
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package scommons.react.test

import scommons.react.{FunctionComponent, ReactElement}

import scala.scalajs.js

class TestErrorBoundarySpec extends TestSpec with TestRendererUtils {

it should "render children if no errors" in {
//when
val result = createTestRenderer(<(TestErrorBoundary())()(
"some child"
)).root

//then
inside(result.children.toList) { case List(child) =>
child shouldBe "some child"
}
}

it should "render error details if error during render" in {
//given
val errorComp = new FunctionComponent[Unit] {
protected def render(props: Props): ReactElement = {
throw new IllegalArgumentException("test error")
}
}

// suppress intended error
// see: https://github.com/facebook/react/issues/11098#issuecomment-412682721
val savedConsoleError = js.Dynamic.global.console.error
js.Dynamic.global.console.error = { _: js.Any =>
}

//when
val result = testRender(<(TestErrorBoundary())()(
<(errorComp())()()
))

//then
js.Dynamic.global.console.error = savedConsoleError

assertNativeComponent(result,
<.div()(
"java.lang.IllegalArgumentException: test error"
)
)
}
}

0 comments on commit 7e2c823

Please sign in to comment.