【问题标题】:Constants are undefined while testing using Enzyme + React Native + Jest使用 Enzyme + React Native + Jest 测试时常量未定义
【发布时间】:2019-01-16 01:08:03
【问题描述】:

我想用 Enzyme 和 Jest 对我的 React Native 组件进行单元测试。

它是一个二维码扫描器,扫描成功后调用一个函数。此函数与服务器通信并返回响应。然后它使用switch 语句来确定下一步要做什么。当我只是使用该应用程序时,该组件及其功能可以正常工作。但是这个函数的单元测试失败了,因为所有的常量都是未定义的。我该如何解决这个问题?

作为参考,这里是我的单元测试的代码(为了清楚起见,去掉了):

import React from "react";
import { shallow } from "enzyme";
import { Alert, View } from "react-native";

import * as qrCodeFunctions from "../../api/qrCodes/qrCodes";
import { ScannerScreen } from "./ScannerScreen";

Alert.alert = jest.fn();

const createTestProps = props => ({
  navigation: { navigate: jest.fn() },
  setData: jest.fn(),
  ...props
});

describe("ScannerScreen", () => {
  describe("rendering", () => {
    let wrapper;
    let props;
    beforeEach(() => {
      props = createTestProps();
      wrapper = shallow(<ScannerScreen {...props} />);
    });

    it("should render a <View />", () => {
      expect(wrapper.find(View)).toHaveLength(1);
    });

    it("should render a <QRCodeScanner />", () => {
      expect(wrapper.find("QRCodeScanner")).toHaveLength(1);
    });
  });

  describe("interaction", () => {
    let wrapper;
    let props;
    beforeEach(() => {
      props = createTestProps();
      wrapper = shallow(<ScannerScreen {...props} />);
    });

    afterEach(() => {
      jest.clearAllMocks();
    });

    describe("scanning the qr code", () => {
      describe("data received", () => {
        qrCodeFunctions.executeQRCodeFunction = jest.fn(
          () =>
            new Promise(resolve =>
              resolve({
                entities: {
                  houses: {
                    "b813d3d1-9fdb-47bf-92ee-f7cb8bd6564b": {
                      category: "villa",
                      price: 2.400.000,
                      uuid: "b813d3d1-9fdb-47bf-92ee-f7cb8bd6564b"
                    }
                  },
                  ...
                },
                result: {
                  detail: "Successfully received villas.",
                  qrCodeData: "aeb1717f-480f-415f-9d15-00906750cae2"
                }
              })
            )
        );
        it("should dispatch an event to set the data and show an alert", () => {
          wrapper.instance().onRead({ data: { v1QRCodeData: "abc" } });
          expect(qrCodeFunctions.executeQRCodeFunction).toHaveBeenCalledTimes(1);
          expect(props.setData).toHaveBeenCalledTimes(1);
          expect(Alert.alert).toHaveBeenCalledTimes(1);
        });
      });
    });
  });
});

props.setData 应该(并且在不进行单元测试时被调用)取决于 switch 语句,就像这样:

  onRead = e => {
    executeQRCodeFunction(e.data.v1QRCodeData)
      .then(data => {
        console.log(data.result);
        console.log(SERVER_VALUES_QR_CODE_DETAIL_VILLAS_RECEIVED);
        console.log(data.result.detail);
        console.log(data.result.detail == SERVER_VALUES_QR_CODE_DETAIL_VILLAS_RECEIVED);
        switch (data.result.detail) {
          case SERVER_VALUES_QR_CODE_DETAIL_VILLAS_RECEIVED:
            this.villasReceived(data);
            break;
          ...
          default:
            alert(data.result);
        }
      })
      .catch(error => {
        alert(error);
      });
  };

函数villasReceived 然后调用setData。但是在单元测试中这永远不会发生,因为 switch case 总是引用默认情况。此外,控制台日志的结果是,data.resultdata.result.detail 是正确的,但比较的是 false 和常量 undefined

【问题讨论】:

    标签: unit-testing react-native constants jestjs enzyme


    【解决方案1】:

    遇到了类似的问题;我的 Jest 测试在我的一个模块的这一行中以 TypeError: Cannot read property 'manifest' of undefined 失败:

    import { Constants } from 'expo';
    
    ...
    
      const storeVersion = Constants.manifest.version;    // test fails here
    
    ...
    

    解决方案

    您可以在 Jest 文档中关注 mock a node module

    我创建了一个文件\__mocks__\expo.js__mocks__ 文件夹需要与node_modules 文件夹相邻),其中包含以下内容:

    const Constants = {
      manifest: {
        version: '1.0.0',
      },
    };
    
    export {
      Constants
    };
    

    显然你会构造一个包含你需要的任何属性的虚拟常量对象。

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2020-08-07
      • 2016-12-14
      • 2019-01-26
      • 2019-02-20
      • 1970-01-01
      • 2017-02-12
      • 2017-11-26
      • 1970-01-01
      相关资源
      最近更新 更多