【问题标题】:How to do jest testing in react native?如何在本机反应中进行开玩笑测试?
【发布时间】:2020-10-30 09:40:39
【问题描述】:

我写了一个简单的代码来测试。

这是我的 App.js:

const App: () => React$Node = () => {

  function sum(a, b) {
     alert(a + b);
     return a + b;
  }

  return (
     <>
        <Button
          title="Sum"
          onPress={() => {sum(1,2)}}
        />
       
  );

这是我在 __tests__ 文件夹中的 App-test.js:

import 'react-native';

const sum = require('../App');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

当我运行npm test 时,我收到此错误TypeError: sum is not a function。谁能帮忙。

注意:当我在我的 android 手机上运行它时,它可以正常工作并在警告框中显示 3。

【问题讨论】:

  • 你似乎错过了结束&lt;/&gt;。添加后是否有效?
  • 哪里需要关闭
  • 不,它不起作用。

标签: react-native jestjs


【解决方案1】:

这是因为您正在从您的 App 文件中导入 sum,但它不是您编写的导出方法。

你可以这样做:

export const sum = (a, b) => {
   alert(a + b);
   return a + b;
}

export const App = () => (
   <Button
      title="Sum"
      onPress={() => {sum(1,2)}}
   />
);

并在您的测试文件中像这样使用它:

import { sum } from '../App'

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

它与 React Native 没有特别的联系,因为您只是尝试测试一种特定的方法,它可以与任何框架一起使用。

【讨论】:

    猜你喜欢
    • 2017-01-25
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2021-04-27
    • 1970-01-01
    • 2018-07-22
    • 2019-11-22
    相关资源
    最近更新 更多