【问题标题】:How to run Jest test for react-native and web如何为 react-native 和 web 运行 Jest 测试
【发布时间】:2017-01-05 10:15:33
【问题描述】:

我想为 Button.js、Button.ios.js、Button.androind.js 运行我的测试,并为不同的平台拍摄单独的快照。我该怎么做?

import "react-native";
import React from "react";
import renderer from "react-test-renderer";
import Button from "..../Button";

test('Example of test', () => {
    const c = renderer.create(
        <Button text="asd" />
    );
    expect(c.toJSON()).toMatchSnapshot();
});

此示例仅为原生 Button 创建快照,并忽略常规 HTML 组件。

版本:

 "react-native": "^0.39.2",
 "jest": "^18.0.0",

【问题讨论】:

  • 反应原生版本?
  • @Codesingh,反应原生:^0.39.2
  • 你升级 react native 是为了开玩笑吗?
  • @Codesingh,是的
  • 给我看看你的 package.json

标签: reactjs react-native jestjs


【解决方案1】:

假设您使用 react-native-web 来获取 HTML 输出,您应该知道 Jest 实际上不会通过 webpack 运行您的 react-native 代码,因此它不会处理 react-native -> react-native -web 别名,因此您永远不会在快照中看到实际的 HTML。

也就是说,您仍然可以确保您的代码在您选择的平台上按预期运行。在我们的例子中,我们有时会为 android 和/或 web 提供不同的代码分支。我们构建了这个简单的助手,让我们可以轻松地模拟不同的平台:

const withPlatform = (platform: string, testFunction: () => void) => {
  const origOS = Platform.OS;
  Platform.OS = platform;
  try {
    testFunction();
  } finally { // eslint-disable-line  brace-style
    Platform.OS = origOS;
  }
};

导入测试后,您可以做一些很酷的事情,例如:

  describe('on the web', () => {
    it('should render correctly', () => {
      withPlatform('web', () => {
        expect(renderer(<SomeComponent />)).toMatchSnapshot(); 
      });
    });
  });

【讨论】:

    猜你喜欢
    • 2020-07-17
    • 2019-07-07
    • 2018-02-09
    • 1970-01-01
    • 2019-01-26
    • 2018-12-11
    • 2020-06-01
    • 2021-09-20
    • 2020-10-26
    相关资源
    最近更新 更多