当我声明一个本机Java模块时,新代码没有通过单元测试,我得到了一个奇怪的异常。基本上我从NativeModules
导入的React Native都缺少定义:所以单元测试失败,因为TypeError: Cannot read property 'HelloWorld' of undefined
复制步骤:
import { NativeModules } from 'react-native';
const Thing = NativeModules.SomeModule;
export const helloWorld = (addedText: string) => {
return Thing.HelloWorld(addedText);
};
export default Thing;
但是错误是
TypeError: Cannot read property 'HelloWorld' of undefined
4 |
5 | export const helloWorld = (addedText: string) => {
> 6 | return Thing.HelloWorld(addedText);
| ^
7 | };
8 |
9 | export default Thing;
实际的Java是
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");
}
}
}
和这个运行很好(当你运行它的时候),但是单元测试讨厌它。问题似乎是React Native测试缺乏对const helloWorld = (addedText: string) => { return Thing.HelloWorld(addedText); };
结构的认识,所以我尽职尽责地制作了这个d.ts
来帮助
declare namespace Thing {
function helloWorld(addedText: string): void;
}
但是在单元测试时仍然失败,我觉得简单地假设这被忽略了是错误的,所以我假设我一定是实现了一些错误的东西。谁能告诉我做这件事的正确方法?
答案是模拟出函数
测试文件中的,(对react-native中调用helloWorld("bob chips")
的代码的任何部分进行测试)(即不是导出的地方),您必须模拟出Java模块,如下所示。请注意,在启动失败测试的文件顶部,这是全局的(一次)-也许您将helloWorld("bob chips")
放在Place.tsx
中,如果这样,也许Place.test.tsx
会失败-因为它引用了helloWorld("bob chips")
,如果在有测试失败的文件中-在Place.test.tsx
中-执行此一次在文件顶部:
jest.mock('react-native', () => {
const RN = jest.requireActual('react-native');
RN.NativeModules.SomeModule = {
HelloWorld: jest.fn(),
};
// mock modules created through UIManager
RN.UIManager.getViewManagerConfig = (name) => {
if (name === 'SomeModule') {
return { HelloWorld: jest.fn() };
}
return {};
};
return RN;
});
然后suppresses
尝试测试它,并允许您在java
中编写测试来补偿