react-native - 使用 Jest 模拟命名导入

标签 react-native jestjs expo es6-modules

我有一个看起来有点像这样的“notifications.js”模块:

import { Notifications, Permissions } from 'expo'

export function setLocalNotification(storage = AsyncStorage) {
  return storage
    .getItem(NOTIFICATION_KEY)
    .then(JSON.parse)
    .then(data => {
      if (data === null) {
        return Permissions.askAsync(
          Permissions.NOTIFICATIONS
        ).then(({ status }) => {
          if (status === 'granted') {
            Notifications.cancelAllScheduledNotificationsAsync()
            ...etc.
在我的测试中,我想模拟 Permissions 和 Notifications,这样我就可以在 notification.spec.js 中做这样的事情:
import { setLocalNotification } from './notifications'
import mockAsyncStorage from '../mock/AsyncStorage'

it('correctly cancels pending notifications', done => {
  setLocalNotification(mockAsyncStorage).then(done())
  expect(Permissions.askAsync).toBeCalled()
  expect(Notifications.cancelAllScheduledNotificationsAsync)
    .toBeCalled()
})
我用 jest.mock 尝试了各种方法和 jest.setMock但我似乎无法让这个工作。如何以所需的方式模拟这些命名导入?例如,我试过这个:
jest.setMock('Permissions', () => ({
  askAsync: jest
    .fn()
    .mockImplementationOnce(() => ({ status: 'granted' }))
}))
但这不起作用。它抛出
'module Permissions cannot be found from notifications.spec.js'
如果我尝试模拟整个 expo 模块,模拟函数 expect().toBeCalled()返回假。

最佳答案

你必须模拟模块 'expo'

jest.mock('expo', ()=>({
  Permissions: {
     askAsync: jest.fn()
  }
}))

关于react-native - 使用 Jest 模拟命名导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46761107/

相关文章:

javascript - VSCode如何禁用/删除 "react/cjs/react.development"自动完成

react-native - 如何更新 rnfirebase admob 以支持 iOS 14 AppTrackingTransparency

visual-studio-code - vscode 开 Jest 扩展不能正常工作

javascript - 如何使用 React.createElement() 测试在 Render 中创建的子 React 组件

javascript - 尝试测试异步函数抛出时 Jest 测试失败

ios - 如何在EXPO中重建iOS?

react-native - 任务 ':app:processDebugResources' 执行失败。 > 安卓资源链接失败可以再构建RN安卓版

android - 运行ADB时出错:未找到Android设备-EXPO-CLI Linux

javascript - 如何使用 react-native 和 javascript 在应用程序的主页中添加弹出窗口?

javascript - react native : Calling setState in FlatList much slower than setState in ScrollView