美文网首页
[React-Native]Jest Unit Test

[React-Native]Jest Unit Test

作者: 猎手Andy | 来源:发表于2019-11-02 08:56 被阅读0次

package.json 关注 devDependencies 和 jest部分

{
  "name": "xxx",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "build:ios": "react-native bundle --entry-file='index.js' --bundle-output='./ios/xxx/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'",
    "build:android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res",
    "test": "jest --colors --testNamePattern --updateSnapshot",
    "test:debug": "jest --colors --testNamePattern --updateSnapshot --runInBand",
    "test:debugW": "jest --colors --testNamePattern --updateSnapshot --runInBand --watch",
    "test:debugger": "node --inspect-brk node_modules/.bin/babel-jest  --colors --testNamePattern --updateSnapshot --runInBand",
    "test:report": "jest --colors --coverage --testNamePattern --updateSnapshot",
    "android:build": "cd android && rm -rf app/src/main/res/drawable-*/node_modules* && rm -rf app/src/main/res/drawable-*/src_images* && ./gradlew assembleRelease",
    "android:install": "cd android && ./gradlew assembleRelease && ./gradlew installRelease",
    "android:devices": "$ANDROID_HOME/platform-tools/adb devices",
    "android:logcat": "$ANDROID_HOME/platform-tools/adb logcat *:S ReactNative:V ReactNativeJS:V",
    "android:shake": "$ANDROID_HOME/platform-tools/adb devices | grep '\\t' | awk '{print $1}' | sed 's/\\s//g' | xargs -I {} $ANDROID_HOME/platform-tools/adb -s {} shell input keyevent 82"
  },
  "rnpm": {
    "assets": [
    ]
  },
  "dependencies": {
    "@react-native-community/async-storage": "1.5.1",
    "abortcontroller-polyfill": "1.3.0",
    "i18n-js": "3.2.2",
    "lottie-react-native": "2.6.1",
    "prop-types": "15.7.2",
    "ramda": "0.25.0",
    "react": "16.8.5",
    "react-native": "0.57.8",
    "react-native-auto-scrolling": "1.1.0",
    "react-native-camera": "1.13.1",
    "react-native-gesture-handler": "1.2.2",
    "react-native-keychain": "3.1.3",
    "react-native-localize": "1.1.2",
    "react-native-location": "2.3.0",
    "react-native-qrcode-scanner": "1.1.0",
    "react-native-search-box": "0.0.19",
    "react-native-svg": "8.0.11",
    "react-native-svg-charts": "5.2.0",
    "react-native-swipeout": "2.3.6",
    "react-native-swiper": "1.5.14",
    "react-native-vector-icons": "6.4.2",
    "react-navigation": "3.11.0",
    "react-redux": "5.1.1",
    "redux": "4.0.1",
    "redux-persist": "5.10.0",
    "redux-thunk": "2.3.0",
    "seamless-immutable": "7.1.4"
  },
  "devDependencies": {
    "axios": "^0.18.0",
    "babel-eslint": "^10.0.1",
    "babel-jest": "^23.6.0",
    "enzyme": "^3.7.0",
    "enzyme-adapter-react-16": "^1.6.0",
    "enzyme-async-helpers": "^0.9.1",
    "enzyme-to-json": "^3.3.4",
    "eslint": "^5.3.0",
    "eslint-config-airbnb": "17.1.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jsx-a11y": "^6.1.1",
    "eslint-plugin-react": "^7.11.0",
    "eslint-plugin-react-native": "^3.5.0",
    "fetch-mock": "^7.2.2",
    "jest": "^23.6.0",
    "jest-cli": "^23.6.0",
    "jest-junit": "^5.2.0",
    "metro-react-native-babel-preset": "^0.49.0",
    "moxios": "^0.4.0",
    "react-dom": "16.8.5",
    "react-test-renderer": "16.8.5",
    "redux-mock-store": "^1.5.3"
  },
  "jest": {
    "preset": "react-native",
    "verbose": true,
    "setupTestFrameworkScriptFile": "./src/setupTests.js",
    "globals": {
      "window": false,
      "document": false
    },
    "moduleDirectories": [
      "node_modules",
      "src"
    ],
    "coverageReporters": [
      "text",
      "text-summary",
      "lcov"
    ],
    "coverageDirectory": "./target",
    "transform": {
      "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
    },
    "moduleNameMapper": {
      "i18n": "<rootDir>/src/__mocks__/i18n.js",
      "react-navigation": "<rootDir>/src/__mocks__/components/reactNavigationMock.js",
      "geography": "<rootDir>/src/__mocks__/components/geographyUtilMock.js"
    }
  }
}

Visual Studio Code的debug

指定具体的测试文件"src/test/path/to/your/test.spec.js",单步调试:

.vscode下的launch.json

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug Jest Tests",
      "type": "node",
      "request": "launch",
      "runtimeArgs": [
        "--inspect-brk",
        "${workspaceRoot}/node_modules/.bin/jest",
        "--runInBand",
        "src/__test__/path/to/your/test.spec.js"
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "port": 9229
    }
  ]
}
image.png

监测文件修改,自动测试已修改测试文件

npm run test:debugW src/__test__/path/to/your/test.spec.js

基本套路

describe('Rendering', () => {
  const { XXXContainer } = require('../../../../features/xxx/containers/xxx');
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(
      <XXXContainer {...props} />
    );
  });
  afterEach(() => {
    jest.resetAllMocks();
   jest.clearAllMocks();
  });

  it('Check props', () => {

  });
});

填一些坑吧

1. 组件必须显示定义构造函数,否则你会怀疑人生

没有困难制造困难。。。

constructor(props) {
    super(props);
  }

2. Container的引用方法

export class XXXContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      refreshing: false
    };
  }
// 此处省略一万行....
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(XXXContainer);

测试文件引用的正确姿势是:别忘了 {}

import { XXXContainer } from '../../../../features/goods/containers/XXX';

3. mock第三方代码

比如你的组件引用了其他的组件或工具方法:

姿势一:

const ThirdParty = require('../path/to/thirdParty').default;
ThirdParty.getProfile = jest.fn().mockReturnValue({ name: 'Tom' });

姿势二:

jest.mock('../path/to/thirdParty', () => ({
  getProfile : jest.fn().mockReturnValue({ name: 'Tom' }),
}));

4. mock 原生代码(iOS/Android nativeModules)

import { NativeModules } from 'react-native';

NativeModules.PushNotification = {
  isPushNotificationEnabled: jest.fn().mockReturnValue(true),
};

----------------END---------------------

相关文章

网友评论

      本文标题:[React-Native]Jest Unit Test

      本文链接:https://www.haomeiwen.com/subject/lydcbctx.html