测试Apple推送通知

cli*_*ray 5 mongoose apple-push-notifications node.js coffeescript apnagent

我使用node.js(服务器框架)和mongoose.js(基于mongo的模式建模)作为iOS应用程序的后端,我使用Mocha(测试框架)来确保一切正常.

我真正想知道的,并且找不到任何文档,是如何在服务器上测试推送通知是否正确发送.我正在使用apnagent,目前我可以看到通过手动检查我的设备正确发送推送通知,但我很难找到一种自动方式来测试它们是否正常工作.


这可能足以说明在高层次上回答需要做什么.但如果不是这里是实际的代码:

Mongoose Model在创建时触发推送通知:

#this code is called after this model is saved in mongodb
eventModel.post 'save', (doc) ->
  #push the message
  sendMessageToDevice = (event, token) ->
    message =
      event_body:
        eventId: event._id
        lat: event.lngLat[1]
        lng: event.lngLat[0]
    agent.createMessage()
      .device(token)
      .alert('New Event! ' + event.description)
      .set(message)
      .send()

  #cycle through the users to push to
  #get all the unique device tokens in the database for APN
  users.getAllUniqueDeviceTokens (error, devices) ->
    if error then return util.handleError error
    console.log "Sending push notices to all devices (%d):", devices.length
    console.log devices
    for token in devices
      sendMessageToDevice doc, token

    #send some verification here that the code ran correctly???
Run Code Online (Sandbox Code Playgroud)

然后在我的Mocha测试文件中,我有:

it 'should receive push notification from fort creation', (done) ->
    #some logic here to verify that push notifications were sent
    done()
Run Code Online (Sandbox Code Playgroud)

Rob*_*ann 3

在许多情况下,在编写测试时,验证操作是否确实发生(即推送通知已发送)要么是不可能的,要么太危险。想象一下为命令编写一个单元测试rm,您希望确保操作rm -rf /成功。显然,您不能让此操作发生并验证您的根分区确实是空的!

然而,您可以做的(实际上应该做的)是验证完成任务所需的任何命令、例程或其他操作是否被正确调用,而不是实际允许它们发生。

在您的特定情况下,您不需要验证推送通知是否已发送,因为您的应用程序不负责通知的发送。但是,您可以测试推送通知是否已正确传送到推送服务器。

因此,您不是测试是否成功交付,而是测试

  1. 传出请求的格式是否正确(即 JSON 有效)
  2. 是否包含您期望它包含的数据(即 JSON 中的字段存在并且包含期望的数据)
  3. 是否包含服务器所需的认证token
  4. 目标服务器是否正确(即您确实将数据发送到 xxx.apple.com 而不是本地主机)

理想情况下,这些测试请求甚至不会到达目标服务器 - 这样做意味着您依赖于两个并不总是完全稳定的因素:

  • 网络连接
  • 目标服务器可用性和适当的功能

过去,我处理这个问题时,首先手动发出正确的请求,捕获响应,然后在单元测试中模拟整个通信(使用 ie nock。这样,我就完全控制了整个通信。