node.js - 测试 Apple 推送通知

标签 node.js mongoose coffeescript apple-push-notifications apnagent

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

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


这可能足以从高层次回答需要做什么的描述。但以防万一这里没有实际代码:

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

#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???

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

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

最佳答案

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

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

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

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

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

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

  • 网络连接
  • 目标服务器可用性和正常功能

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

关于node.js - 测试 Apple 推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29936011/

相关文章:

javascript - 在浏览器和 Node 中运行 CoffeeScript 类

javascript - 在 Node.js 中的 res.render() 之后使用 server-sent-events

node.js - 如何在 NODE.js 服务器上使用 Google 字体?

javascript - Node js 和 mustache

javascript - Mongodb/mongoose insert 不是函数

javascript - 在没有 jQuery 的情况下在 AngularJS 中扩展 DOM 对象的推荐方法?

javascript - 如何使用任何 javascript 库在没有 iframe 的情况下在网站中嵌入 powerbi 报告?

javascript - 如何使用带有严格 : false schema? 的 mongoose 将字段添加到 mongoDB 文档中

coffeescript - 观看cakefile任务中的CoffeeScript文件时输出