 @testable import Promise
 
 class PromiseRaceTests: XCTestCase {
+    
+    func makeTimeoutError() -> NSError {
+        return NSError(domain: "com.khanlou.Promise", code: -1111, userInfo: [ NSLocalizedDescriptionKey: "Timed out" ])
+    }
 
     func testRace() {
         weak var expectation = expectationWithDescription("`Promise.race` should fulfill as soon as the first promise is fulfilled.")

        
        let promise1 = Promise<Int>(work: { fulfill, reject in
            delay(0.05) {
                reject(NSError(domain: "com.khanlou.Promise", code: -1111, userInfo: [ NSLocalizedDescriptionKey: "Timed out" ]))
            }
        })
        let promise2 = Promise<()>.delay(0.1).then({ 2 })

        waitForExpectationsWithTimeout(1, handler: nil)
        XCTAssert(final.isRejected)
    }
    
    func testInstantResolve() {
        weak var expectation = expectationWithDescription("`Promise.race` should reject as soon as the first promise is reject.")
        
        let promise1 = Promise<Int>(value: 1)
        let promise2 = Promise<()>.delay(0.1).then({ 5 })
        
        let final = Promise<Int>.race([promise1, promise2])
        
        final.then({ _ in
            expectation?.fulfill()
        })
        
        waitForExpectationsWithTimeout(1, handler: nil)
        XCTAssert(final.isFulfilled)
        XCTAssertEqual(final.value, 1)
    }
    
    func testInstantReject() {
        weak var expectation = expectationWithDescription("`Promise.race` should reject as soon as the first promise is reject.")
        
        let promise1 = Promise<Int>(error: makeTimeoutError())
        let promise2 = Promise<()>.delay(0.1).then({ 5 })
        
        let final = Promise<Int>.race([promise1, promise2])
        
        final.onFailure({ _ in
            expectation?.fulfill()
        })
        
        waitForExpectationsWithTimeout(1, handler: nil)
        XCTAssert(final.isRejected)
    }

}
