When I create a Native Java Module, the new code fails unit tests due to a strange anomaly. The issue arises because anything imported from NativeModules
in React Native lacks a definition, resulting in a test failure with the error message:
TypeError: Cannot read property 'HelloWorld' of undefined
To reproduce the problem:
import { NativeModules } from 'react-native';
const Thing = NativeModules.SomeModule;
export const helloWorld = (addedText: string) => {
return Thing.HelloWorld(addedText);
};
export default Thing;
However, the actual Java code is:
public class SomeModule extends ReactContextBaseJavaModule {
SomeModule(ReactApplicationContext context) {
super(context);
}
@Override
public String getName() {
return "SomeModule";
}
void HelloWorld(String addedText){
try {
Log.w("HELLO_WORLD", addedText);
}
catch (Exception e) {
Log.e("DEVICE_MODULE_HELLO_WORLD_FAILED", "HelloWorld() Failed");
}
}
}
This Java code runs fine but the unit tests encounter issues. To address this, I created a declaration file (d.ts
) as follows:
declare namespace Thing {
function helloWorld(addedText: string): void;
}
Despite creating the declaration file, the unit tests still fail. I suspect there may be an incorrect implementation on my part rather than an oversight. Can anyone provide guidance on the correct approach?