1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "ios/web/public/test/js_test_util.h"
7 #import <Foundation/Foundation.h>
9 #import "base/logging.h"
10 #import "base/mac/scoped_nsobject.h"
11 #import "base/time/time.h"
12 #import "ios/web/public/web_state/js/crw_js_injection_manager.h"
13 #import "ios/web/public/web_state/js/crw_js_injection_receiver.h"
16 using base::TimeDelta;
19 // The amount of time (in secs) |evaluate:StringResultHandler:| is given time to
20 // process until the test fails.
21 const NSTimeInterval kTimeout = 5.0;
26 NSString* EvaluateJavaScriptAsString(CRWJSInjectionManager* manager,
28 __block base::scoped_nsobject<NSString> evaluationResult;
29 [manager evaluate:script
30 stringResultHandler:^(NSString* result, NSError* error) {
32 evaluationResult.reset([result copy]);
34 // TODO(shreyasv): This is a temporary solution to have some duplicated code.
35 // The right way to implement this is to use |WaitUntilCondition|. Move to
36 // that when that function lives in ios/.
37 Time startTime = Time::Now();
38 while (!evaluationResult.get() &&
39 (Time::Now() - startTime < TimeDelta::FromSeconds(kTimeout))) {
40 NSDate* beforeDate = [NSDate dateWithTimeIntervalSinceNow:.01];
41 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
42 beforeDate:beforeDate];
44 DCHECK(evaluationResult);
45 return [[evaluationResult retain] autorelease];
48 NSString* EvaluateJavaScriptAsString(CRWJSInjectionReceiver* receiver,
50 base::scoped_nsobject<CRWJSInjectionManager> manager(
51 [[CRWJSInjectionManager alloc] initWithReceiver:receiver]);
52 return EvaluateJavaScriptAsString(manager, script);