Code Push破坏了React Native的Jest测试

8

我已经为Code-push配置了一个应用程序,除了jest测试之外,它运行良好。在渲染应用程序时出现错误,导致测试失败:

TypeError: Cannot read property 'CheckFrequency' of undefined

  at Object.<anonymous> (app/index.js:7:66)
  at Object.<anonymous> (index.ios.js:5:12)
  at Object.<anonymous> (__tests__/index.ios.js:4:12)

在这一行中:
const codePushOptions = { checkFrequency: codePush.CheckFrequency.MANUAL };

测试代码如下:
import App from '../index.ios';

it('renders correctly', () => {
  const tree = renderer.create(
      <App />,
  );
});

1
你需要为CodePush创建一个mock - Xeijp
codePush 变量未定义或不是 JSON。 - RITESH ARORA
@Assem Chelli,你解决了你的问题吗?我自己也遇到了类似的问题... - Tom Hall
@TomHall 还没有。 - Assem
@Olivia 还没有。 - Assem
显示剩余2条评论
4个回答

11

在我集成codePush到我目前正在开发的React Native应用程序时,遇到了这个问题。对我有用的解决方法是:

  1. 创建一个名为__mocks__/react-native-code-push.js的文件。

将以下代码添加到文件中:

const codePush = {
  InstallMode: {ON_NEXT_RESTART: 'ON_APP_RESTART'},
  CheckFrequency: {ON_APP_RESUME: 'ON_APP_RESUME'}
};

const cb = _ => app => app;
Object.assign(cb, codePush);
export default cb;

在我的index.js文件中,我有:

import codePush from 'react-native-code-push';
import MyApp from './src/'

const codePushOptions = {
  installMode: codePush.InstallMode.ON_NEXT_RESTART,
  checkFrequency: codePush.CheckFrequency.ON_APP_RESUME
};

export default codePush(codePushOptions)(MyApp);

luizParreira,你在哪里创建了__mocks__目录?你需要将它链接到任何地方吗? - Josh Wang
1
在根目录下创建__mocks__文件夹。请参考https://facebook.github.io/jest/docs/en/manual-mocks.html。 - Josh Wang

9

Tom Hall所描述的情况类似,这个模拟测试对我是有效的:

jest.mock('react-native-code-push', () => {
  const cp = (_: any) => (app: any) => app;
  Object.assign(cp, {
    InstallMode: {},
    CheckFrequency: {},
    SyncStatus: {},
    UpdateState: {},
    DeploymentStatus: {},
    DEFAULT_UPDATE_DIALOG: {},

    checkForUpdate: jest.fn(),
    codePushify: jest.fn(),
    getConfiguration: jest.fn(),
    getCurrentPackage: jest.fn(),
    getUpdateMetadata: jest.fn(),
    log: jest.fn(),
    notifyAppReady: jest.fn(),
    notifyApplicationReady: jest.fn(),
    sync: jest.fn(),
  });
  return cp;
});

3
为什么要柯里化?它不是这样传递的。将其修改为 const cp = (app: any) => app; 后,就可以传递了。 - adambene

1

在您的测试中,在import App from '../index.ios';下面添加以下内容:

jest.mock('react-native-code-push', () => {
    return jest.fn(() => ({
        InstallMode: jest.fn(),
        CheckFrequency: jest.fn(),
        CodePushComponent: jest.fn(),
        codePushify: jest.fn()
    }));
});

我相信这仍然会导致错误 TypeError: Cannot read property 'MANUAL' of undefined - Keith

0
你需要一个模拟环境来使code-push正常工作,这一行代码CodePush.CheckFrequency.MANUAL将总是产生null

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接