簡體   English   中英

如何使用 Jest 測試庫 React Native

[英]How to test a library React Native using Jest

我嘗試使用 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 不是函數

誰能幫我解決這個問題,非常感謝!

嘗試

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 我不確定您在上面的測試中測試的是什么,但這是模擬您不想在測試中運行的函數的好方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM