Using Jest to mock named imports

ぐ巨炮叔叔 提交于 2019-12-12 20:50:02

问题


I have a 'notifications.js' module that looks a bit like this:

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.

In my test, I want to mock Permissions and Notifications so I can do something like this in notifications.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()
})

I've tried various things using jest.mock and jest.setMock but I can't seem to get this working. How do I go about mocking these named imports in the desired way? For instance, I've tried this:

jest.setMock('Permissions', () => ({
  askAsync: jest
    .fn()
    .mockImplementationOnce(() => ({ status: 'granted' }))
}))

But that doesn't work. It throws

'module Permissions cannot be found from notifications.spec.js'

And if I try to mock the entire expo module, the mocked functions expect().toBeCalled() returns false.


回答1:


You have to mock the module 'expo'

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


来源:https://stackoverflow.com/questions/46761107/using-jest-to-mock-named-imports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!