2016-08-15 84 views
3

需要模擬1個反應組件,只是簡單的虛擬模擬,用於快照測試。Jest.mock外部變量引用

當我嘗試調用React.Component模擬功能,我得到了一個錯誤:

The second argument of jest.mock() is not allowed to reference any outside variables.

但如果我叫require('react').Component,即作品! 有沒有人類的方式來正確地做到這一點?

我的代碼:

//This one fails 
import React from ('react'); 
... 
    jest.mock('...',() => { return class ... extends React.Component { 
      render(){ 
       return <span/> 
      } 

    }}); 

//This one works 
import React from ('react'); 
... 
jest.mock('...',() => { return class ... extends require('react').Component { 
      render(){ 
       return <span/> 
      } 

    }}); 

回答

1

Based on GitHub thread

This used to be a bug that we fixed. In a mock you can only require things locally and you aren't allowed to access external variables.

你可以改變你的代碼,這樣使它工作

jest.mock('...',() => { 
    const React = require ('react') 
    return class ... extends React.Component { 
    render() { 
     return <span /> 
    }  
    } 
}) 
+0

但是,如果你想改變一個變量?認爲你想要模擬一個具有一個對象的函數,並且爲了測試目的,在一次測試中它必須是真實的,而其他的則是假的。我現在該怎麼做? –