【问题标题】:How to test a library React Native using Jest如何使用 Jest 测试库 React Native
【发布时间】:2022-06-11 15:02:24
【问题描述】:

我尝试使用 Jest 测试 React Native 库,但它显示错误,谁能帮我解决我的问题。

这是我的功能代码:

export const createChannel = (): void => {
  PushNotification.createChannel({
    channelId: 'test-channel',
    channelName: 'Test Channel',
    vibrate: true,
  });
};

我正在对这个函数使用 react-native-push-notification 库

这是我的测试代码:

import PushNotification from 'react-native-push-notification';
import {createChannel} from '../src/functions/PomodoroFunction';
jest.mock('react-native-push-notification', () => 'PushNotification.createChannel');

describe('Create Channel unit test', () => {
    it('Should be called',()=>{
      const mockFN = createChannel()
      expect(mockFN).toHaveBeenCalled();
    })
  });

显示错误:TypeError: _reactNativePushNotification.default.createChannel 不是函数

谁能帮我解决这个问题,非常感谢!

【问题讨论】:

    标签: javascript react-native jestjs


    【解决方案1】:

    试试

    import * as PushNotification from 'react-native-push-notification';
    ...
    const create = jest.fn();
    const rnpn = jest.spyOn(PushNotification, 'default').mockImplementation(() => {
      return { createChannel: create } as any;
    });
    ...
    

    然后在您的测试中使用create。我不确定您在上面的测试中测试的是什么,但这是模拟您不想在测试中运行的函数的好方法。

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 2021-09-20
      • 2020-10-26
      • 2018-02-09
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      相关资源
      最近更新 更多