I want to do some unit test regarding WKWebView evaluateJavaScript JS code. JS code runs well in ViewController.m, but failed in unit test with error of “Domain=WKErrorDomain Code=5 “JavaScript execution returned a result of an unsupported type” UserInfo={NSLocalizedDescription=JavaScript execution returned a result of an unsupported type}”.
I change the JS code to a very simple string @"(function(){return 5;})()", still failed.
// ViewController.m
// works with result of 5
- (void)viewDidLoad {
[super viewDidLoad];
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
wkWebView.navigationDelegate = self;
[self.view addSubview:wkWebView];
[wkWebView loadHTMLString:@"<html></html>" baseURL:nil];
NSString *script = @"(function(){return 5;})()";
[wkWebView evaluateJavaScript:script completionHandler:^(id result, NSError * _Nullable error) {
NSString *value = [NSString stringWithFormat:@"%@", result] ;
NSLog(@"Value %@ %@", value, error);
}];
}
// unit test
// failed with error of unsupported type
- (void)testExample {
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0,0,300,300) configuration:configuration];
[wkWebView loadHTMLString:@"<html></html>" baseURL:nil];
NSString *script = @"(function(){return 5;})()";
[wkWebView evaluateJavaScript:script completionHandler:^(id result, NSError * _Nullable error) {
NSString *value = [NSString stringWithFormat:@"%@", result] ;
NSLog(@"Value %@ %@", value, error);
XCTAssertEqualObjects(@"5", value, @"");
}];
}




