2016-08-15 276 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

但是,如果你想改变一个变量?认为你想要模拟一个具有一个对象的函数,并且为了测试目的,在一次测试中它必须是真实的,而其他的则是假的。我现在该怎么做? –