使用 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屋!