Quick/Nimble notification userInfo testing

匆匆过客 提交于 2020-12-10 15:58:48

问题


I was looking at the notifications support in quick/nimble, e.g.:

expect {
    NotificationCenter.default.postNotification(testNotification)
}.to(postNotifications(equal([testNotification]))

Is there a way to get my hands on the notification that is returned to inspect the userInfo? My goal is to invoke a method that posts a notification, and then inspect that notification userInfo and make sure that the key/value pairs are correct.

Quick: 2.1.0
Nimble: 8.0.1


回答1:


I ended up doing this:

func equalName(_ expectedName: Notification.Name, condition: @escaping (([AnyHashable: Any]) -> Bool)) -> Predicate<[Notification]> {
    return Predicate.define("equal <\(stringify(expectedName))>") { actualExpression, msg in
        guard let actualValue = try actualExpression.evaluate() else {
            return PredicateResult(status: .fail, message: msg)
        }

        let actualNames = actualValue
            .filter { $0.name == expectedName }
            .filter { notification in
                guard let userInfo = notification.userInfo else {
                    return false
                }

                return condition(userInfo)
            }
            .compactMap { $0.name }
        let matches = actualNames.contains(expectedName)
        return PredicateResult(bool: matches, message: msg)
    }
}

and then at the call site you can provide the condition..



来源:https://stackoverflow.com/questions/57151281/quick-nimble-notification-userinfo-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!