使用Jest模拟命名的导入 [英] Using Jest to mock named imports
问题描述
我有一个'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.mock
和jest.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屋!