问题
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