react-native/Examples/UIExplorer/UIExplorerUnitTests/RCTBridgeTests.m

227 lines
6.3 KiB
Mathematica
Raw Normal View History

/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#import <Foundation/Foundation.h>
#import <XCTest/XCTest.h>
#import "RCTBridge.h"
#import "RCTBridge+Private.h"
#import "RCTBridgeModule.h"
#import "RCTJavaScriptExecutor.h"
#import "RCTUtils.h"
@interface TestExecutor : NSObject <RCTJavaScriptExecutor>
@property (nonatomic, readonly, copy) NSMutableDictionary<NSString *, id> *injectedStuff;
@end
@implementation TestExecutor
RCT_EXPORT_MODULE()
- (void)setUp {}
- (instancetype)init
{
if (self = [super init]) {
_injectedStuff = [NSMutableDictionary dictionary];
}
return self;
}
- (BOOL)isValid
{
return YES;
}
Decouple Module System from Native Calls Summary: The JavaScript ecosystem doesn't have the notion of a built-in native module loader. Even Node is decoupled from its module loader. The module loader system is just JS that runs on top of the global `process` object which has all the built-in goodies. Additionally there is no such thing as a global require. That is something unique to our providesModule system. In other module systems such as node, every require is contextual. Even registered npm names are localized by version. The only global namespace that is accessible to the host environment is the global object. Normally module systems attaches itself onto the hooks provided by the host environment on the global object. Currently, we have two forms of dispatch that reaches directly into the module system. executeJSCall which reaches directly into require. Everything now calls through the BatchedBridge module (except one RCTLog edge case that I will fix). I propose that the executors calls directly onto `BatchedBridge` through an instance on the global so that everything is guaranteed to go through it. It becomes the main communication hub. I also propose that we drop the dynamic requires inside of MessageQueue/BatchBridge and instead have the modules register themselves with the bridge. executeJSCall was originally modeled after the XHP equivalent. The XHP equivalent was designed that way because the act of doing the call was the thing that defined a dependency on the module from the page. However, that is not how React Native works. The JS side is driving the dependencies by virtue of requiring new modules and frameworks and the existence of dependencies is driven by the JS side, so this design doesn't make as much sense. The main driver for this is to be able to introduce a new module system like Prepack's module system. However, it also unlocks the possibility to do dead module elimination even in our current module system. It is currently not possible because we don't know which module might be called from native. Since the module system now becomes decoupled we could publish all our providesModule modules as npm/CommonJS modules using a rewrite script. That's what React Core does. That way people could use any CommonJS bundler such as Webpack, Closure Compiler, Rollup or some new innovation to create a JS bundle. This diff expands the executeJSCalls to the BatchedBridge's three individual pieces to make them first class instead of being dynamic. This removes one layer of abstraction. Hopefully we can also remove more of the things that register themselves with the BatchedBridge (various EventEmitters) and instead have everything go through the public protocol. ReactMethod/RCT_EXPORT_METHOD. public Reviewed By: vjeux Differential Revision: D2717535 fb-gh-sync-id: 70114f05483124f5ac5c4570422bb91a60a727f6
2015-12-08 23:57:34 +00:00
- (void)flushedQueue:(RCTJavaScriptCallback)onComplete
{
onComplete(nil, nil);
}
- (void)callFunctionOnModule:(__unused NSString *)module
method:(__unused NSString *)method
arguments:(__unused NSArray *)args
Decouple Module System from Native Calls Summary: The JavaScript ecosystem doesn't have the notion of a built-in native module loader. Even Node is decoupled from its module loader. The module loader system is just JS that runs on top of the global `process` object which has all the built-in goodies. Additionally there is no such thing as a global require. That is something unique to our providesModule system. In other module systems such as node, every require is contextual. Even registered npm names are localized by version. The only global namespace that is accessible to the host environment is the global object. Normally module systems attaches itself onto the hooks provided by the host environment on the global object. Currently, we have two forms of dispatch that reaches directly into the module system. executeJSCall which reaches directly into require. Everything now calls through the BatchedBridge module (except one RCTLog edge case that I will fix). I propose that the executors calls directly onto `BatchedBridge` through an instance on the global so that everything is guaranteed to go through it. It becomes the main communication hub. I also propose that we drop the dynamic requires inside of MessageQueue/BatchBridge and instead have the modules register themselves with the bridge. executeJSCall was originally modeled after the XHP equivalent. The XHP equivalent was designed that way because the act of doing the call was the thing that defined a dependency on the module from the page. However, that is not how React Native works. The JS side is driving the dependencies by virtue of requiring new modules and frameworks and the existence of dependencies is driven by the JS side, so this design doesn't make as much sense. The main driver for this is to be able to introduce a new module system like Prepack's module system. However, it also unlocks the possibility to do dead module elimination even in our current module system. It is currently not possible because we don't know which module might be called from native. Since the module system now becomes decoupled we could publish all our providesModule modules as npm/CommonJS modules using a rewrite script. That's what React Core does. That way people could use any CommonJS bundler such as Webpack, Closure Compiler, Rollup or some new innovation to create a JS bundle. This diff expands the executeJSCalls to the BatchedBridge's three individual pieces to make them first class instead of being dynamic. This removes one layer of abstraction. Hopefully we can also remove more of the things that register themselves with the BatchedBridge (various EventEmitters) and instead have everything go through the public protocol. ReactMethod/RCT_EXPORT_METHOD. public Reviewed By: vjeux Differential Revision: D2717535 fb-gh-sync-id: 70114f05483124f5ac5c4570422bb91a60a727f6
2015-12-08 23:57:34 +00:00
callback:(RCTJavaScriptCallback)onComplete
{
onComplete(nil, nil);
}
- (void)invokeCallbackID:(__unused NSNumber *)cbID
arguments:(__unused NSArray *)args
Decouple Module System from Native Calls Summary: The JavaScript ecosystem doesn't have the notion of a built-in native module loader. Even Node is decoupled from its module loader. The module loader system is just JS that runs on top of the global `process` object which has all the built-in goodies. Additionally there is no such thing as a global require. That is something unique to our providesModule system. In other module systems such as node, every require is contextual. Even registered npm names are localized by version. The only global namespace that is accessible to the host environment is the global object. Normally module systems attaches itself onto the hooks provided by the host environment on the global object. Currently, we have two forms of dispatch that reaches directly into the module system. executeJSCall which reaches directly into require. Everything now calls through the BatchedBridge module (except one RCTLog edge case that I will fix). I propose that the executors calls directly onto `BatchedBridge` through an instance on the global so that everything is guaranteed to go through it. It becomes the main communication hub. I also propose that we drop the dynamic requires inside of MessageQueue/BatchBridge and instead have the modules register themselves with the bridge. executeJSCall was originally modeled after the XHP equivalent. The XHP equivalent was designed that way because the act of doing the call was the thing that defined a dependency on the module from the page. However, that is not how React Native works. The JS side is driving the dependencies by virtue of requiring new modules and frameworks and the existence of dependencies is driven by the JS side, so this design doesn't make as much sense. The main driver for this is to be able to introduce a new module system like Prepack's module system. However, it also unlocks the possibility to do dead module elimination even in our current module system. It is currently not possible because we don't know which module might be called from native. Since the module system now becomes decoupled we could publish all our providesModule modules as npm/CommonJS modules using a rewrite script. That's what React Core does. That way people could use any CommonJS bundler such as Webpack, Closure Compiler, Rollup or some new innovation to create a JS bundle. This diff expands the executeJSCalls to the BatchedBridge's three individual pieces to make them first class instead of being dynamic. This removes one layer of abstraction. Hopefully we can also remove more of the things that register themselves with the BatchedBridge (various EventEmitters) and instead have everything go through the public protocol. ReactMethod/RCT_EXPORT_METHOD. public Reviewed By: vjeux Differential Revision: D2717535 fb-gh-sync-id: 70114f05483124f5ac5c4570422bb91a60a727f6
2015-12-08 23:57:34 +00:00
callback:(RCTJavaScriptCallback)onComplete
{
onComplete(nil, nil);
}
- (void)executeApplicationScript:(__unused NSString *)script
sourceURL:(__unused NSURL *)url
onComplete:(RCTJavaScriptCompleteBlock)onComplete
{
onComplete(nil);
}
- (void)executeBlockOnJavaScriptQueue:(dispatch_block_t)block
{
block();
}
- (void)injectJSONText:(NSString *)script
asGlobalObjectNamed:(NSString *)objectName
callback:(RCTJavaScriptCompleteBlock)onComplete
{
_injectedStuff[objectName] = script;
onComplete(nil);
}
- (void)invalidate {}
@end
@interface RCTBridgeTests : XCTestCase <RCTBridgeModule>
{
RCTBridge *_bridge;
BOOL _testMethodCalled;
}
@end
@implementation RCTBridgeTests
2015-06-19 11:18:54 +00:00
@synthesize methodQueue = _methodQueue;
2015-06-19 11:18:54 +00:00
RCT_EXPORT_MODULE(TestModule)
- (void)setUp
{
[super setUp];
_bridge = [[RCTBridge alloc] initWithBundleURL:nil
moduleProvider:^{ return @[self]; }
launchOptions:nil];
_bridge.executorClass = [TestExecutor class];
// Force to recreate the executor with the new class
// - reload: doesn't work here since bridge hasn't loaded yet.
[_bridge invalidate];
[_bridge setUp];
}
- (void)tearDown
{
[super tearDown];
[_bridge invalidate];
_testMethodCalled = NO;
}
#define RUN_RUNLOOP_WHILE(CONDITION) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
NSDate *timeout = [[NSDate date] dateByAddingTimeInterval:0.1]; \
while ((CONDITION) && [timeout timeIntervalSinceNow] > 0) { \
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:timeout]; \
} \
_Pragma("clang diagnostic pop")
- (void)testHookRegistration
{
TestExecutor *executor = [_bridge.batchedBridge valueForKey:@"_javaScriptExecutor"];
NSString *injectedStuff;
RUN_RUNLOOP_WHILE(!(injectedStuff = executor.injectedStuff[@"__fbBatchedBridgeConfig"]));
__block NSNumber *testModuleID = nil;
__block NSDictionary<NSString *, id> *testConstants = nil;
__block NSNumber *testMethodID = nil;
NSArray *remoteModuleConfig = RCTJSONParse(injectedStuff, NULL)[@"remoteModuleConfig"];
[remoteModuleConfig enumerateObjectsUsingBlock:^(id moduleConfig, NSUInteger i, BOOL *stop) {
if ([moduleConfig isKindOfClass:[NSArray class]] && [moduleConfig[0] isEqualToString:@"TestModule"]) {
testModuleID = @(i);
testConstants = moduleConfig[1];
testMethodID = @([moduleConfig[2] indexOfObject:@"testMethod"]);
*stop = YES;
}
}];
XCTAssertNotNil(remoteModuleConfig);
XCTAssertNotNil(testModuleID);
XCTAssertNotNil(testConstants);
XCTAssertEqualObjects(testConstants[@"eleventyMillion"], @42);
XCTAssertNotNil(testMethodID);
}
- (void)testCallNativeMethod
{
TestExecutor *executor = [_bridge.batchedBridge valueForKey:@"_javaScriptExecutor"];
NSString *injectedStuff;
RUN_RUNLOOP_WHILE(!(injectedStuff = executor.injectedStuff[@"__fbBatchedBridgeConfig"]));
__block NSNumber *testModuleID = nil;
__block NSNumber *testMethodID = nil;
NSArray *remoteModuleConfig = RCTJSONParse(injectedStuff, NULL)[@"remoteModuleConfig"];
[remoteModuleConfig enumerateObjectsUsingBlock:^(id moduleConfig, NSUInteger i, __unused BOOL *stop) {
if ([moduleConfig isKindOfClass:[NSArray class]] && [moduleConfig[0] isEqualToString:@"TestModule"]) {
testModuleID = @(i);
testMethodID = @([moduleConfig[2] indexOfObject:@"testMethod"]);
*stop = YES;
}
}];
XCTAssertNotNil(testModuleID);
XCTAssertNotNil(testMethodID);
NSArray *args = @[@1234, @5678, @"stringy", @{@"a": @1}, @42];
NSArray *buffer = @[@[testModuleID], @[testMethodID], @[args]];
[_bridge.batchedBridge handleBuffer:buffer];
2015-06-19 11:18:54 +00:00
dispatch_sync(_methodQueue, ^{
// clear the queue
XCTAssertTrue(_testMethodCalled);
});
}
- (void)DISABLED_testBadArgumentsCount
{
//NSArray *bufferWithMissingArgument = @[@[@1], @[@0], @[@[@1234, @5678, @"stringy", @{@"a": @1}/*, @42*/]], @[], @1234567];
//[_bridge handleBuffer:bufferWithMissingArgument];
NSLog(@"WARNING: testBadArgumentsCount is temporarily disabled until we have a better way to test cases that we expect to trigger redbox errors");
}
RCT_EXPORT_METHOD(testMethod:(NSInteger)integer
number:(nonnull NSNumber *)number
string:(NSString *)string
dictionary:(NSDictionary *)dict
callback:(RCTResponseSenderBlock)callback)
{
_testMethodCalled = YES;
XCTAssertTrue(integer == 1234);
XCTAssertEqualObjects(number, @5678);
XCTAssertEqualObjects(string, @"stringy");
XCTAssertEqualObjects(dict, @{@"a": @1});
XCTAssertNotNil(callback);
}
- (NSDictionary<NSString *, id> *)constantsToExport
{
return @{@"eleventyMillion": @42};
}
@end