2017-10-15 135 views
0

我有一个“notifications.js”模块,看起来有点像这样:用玩笑来嘲笑命名进口

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:

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尝试了各种东西,但我似乎无法得到这个工作。我如何着手以所需的方式嘲笑这些命名的导入?例如,我试过这个:

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

但这并不奏效。它抛出

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

如果我试图嘲弄整个世博模块,嘲笑的功能expect().toBeCalled()返回false。

回答

0

你要嘲笑模块'expo'

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

我最初想这一点,但我认为这是行不通的,因为我的测试失败。但事实证明,他们失败了,因为我的执行有一个错误。所以这确实是正确的方法。 – BarthesSimpson