Test WebSocket in PlayFramework

前端 未结 4 1803
梦如初夏
梦如初夏 2021-02-20 16:32

I have a WebSocket in my Play application and I want to write a test for it, but I couldn\'t find any example on how to write such a test. I found a discussion in the play-frame

4条回答
  •  悲哀的现实
    2021-02-20 16:57

    You can retrieve underlying Iteratee,Enumerator and test them directly. This way you don't need to use a browser. You need akka-testkit though, to cope with asynchronous nature of iteratees.

    A Scala example:

    object WebSocket extends Controller {
      def websocket = WebSocket.async[JsValue] { request =>
        Future.successful(Iteratee.ignore[JsValue] -> Enumerator.apply[JsValue](Json.obj("type" -> "error")))   
      }
    }
    
    class WebSocketSpec extends PlaySpecification {    
      "WebSocket" should {
        "respond with error packet" in new WithApplication {
          val request = FakeRequest()
    
          var message: JsValue = null
          val iteratee = Iteratee.foreach[JsValue](chunk => message = chunk)(Akka.system.dispatcher)
    
          Controller.websocket().f(request)(Enumerator.empty[JsValue],iteratee)
    
          TestKit.awaitCond(message == Json.obj("type" -> "error"), 1 second)
        }
      }
    }
    

提交回复
热议问题