使用 Jest 模拟命名导入 [英] Using Jest to mock named imports

查看:38
本文介绍了使用 Jest 模拟命名导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的notifications.js"模块:

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.

在我的测试中,我想模拟权限和通知,这样我就可以在notifications.spec.js 中做这样的事情:

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()
})

我使用 jest.mockjest.setMock 尝试了各种方法,但我似乎无法让它工作.我如何以所需的方式模拟这些命名导入?例如,我试过这个:

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' }))
}))

但这行不通.它抛出

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

如果我尝试模拟整个 expo 模块,模拟的函数 expect().toBeCalled() 返回 false.

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

推荐答案

你必须模拟模块 'expo'

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

这篇关于使用 Jest 模拟命名导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆