【问题标题】:Mocked object can not be accessed directly模拟对象不能直接访问
【发布时间】:2017-11-21 18:53:31
【问题描述】:

在 Jest 中,我有以下测试代码。我导入NativeModules

import { NativeModules } from 'react-native';

然后,在每次测试之前,我都会向其中添加我自己的对象:

 beforeEach(() => {
    NativeModules.Dispatcher = {
        methodA: jest.fn(),
        methodB: jest.fn(),
        methodC: jest.fn()
    };
 });

在我正在测试的源代码中,我导入NativeModules

import { NativeModules } from 'react-native';

我引用了我的模拟对象

class ClassThatIsTested {

   someMethod(parameter) {
      NativeModules.Dispatcher.methodA(parameter);
      //some other code
  }

}

这很好用。但是,如果我尝试直接引用模拟对象:

import { NativeModules } from 'react-native';
const { Dispatcher } = NativeModules;
class ClassThatIsTested {

   someMethod(parameter) {
     Dispatcher.methodA(parameter);
      //some other code
  }

}

失败了:

Dispatcher.methodA is not a function

如果我打印Dispatcher,我会得到undefined

为什么会这样?为什么我不能直接访问模拟对象?

【问题讨论】:

    标签: javascript reactjs react-native jestjs


    【解决方案1】:
    import NativeModules from 'react-native';
    

    不正确,需要import the named export NativeModules,而不是默认导出:

    import {NativeModules} from 'react-native';
    

    【讨论】:

    • 非常抱歉,我的代码复制错误。实际上,我确实使用import {NativeModules} from 'react-native';
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 2015-02-08
    相关资源
    最近更新 更多