2017-08-03 100 views
1

测试功能,我有一个基本的功能:玩笑基础:从组件

组件/ FirstComponent:

sayMyName = (fruit) => { 
    alert("Hello, I'm " + fruit); 
    return fruit; 
} 

当我试着用玩笑来测试它里面FirstComponent.test.js:

import FirstComponent from '../components/FirstComponent'; 

describe('<FirstComponent />',() => { 
    it('tests the only function',() => { 
     FirstComponent.sayMyName = jest.fn(); 
     const value = FirstComponent.sayMyName('orange'); 
     expect(value).toBe('orange'); 
    }); 
}); 

测试说:比较两种不同类型的值。预期的字符串,但收到未定义。

显然我没有导入函数来测试正确的方式?

我不是足够聪明,了解玩笑文件如何测试从组件功能..

有一些简单的方法来从组件导入功能,并测试它?

编辑: 这个作品现在使用“反应测试,渲染”

import FirstComponent from '../components/FirstComponent'; 
import renderer from 'react-test-renderer'; 

describe('<FirstComponent /> functions',() => { 
     it('test the only function',() => { 
      const wrapper = renderer.create(<FirstComponent />); 
      const inst = wrapper.getInstance(); 
      expect(inst.sayMyName('orange')).toMatchSnapshot(); 
     }); 
}) 

回答

1

你存根与一个不返回任何功能。 FirstComponent.sayMyName = jest.fn();

要测试的功能,通常你可以做

// if static etc 
import { sayMyName } from '../foo/bar'; 

describe('bar',() => { 
    it('should do what I like',() => { 
    expect(sayMyName('orange')).toMatchSnapshot(); 
    }); 
}) 

这将存储输出(“橙色”),并断言,每次运行这个测试时,它应该返回橙色。如果您的函数停止执行或返回其他内容,则快照将有所不同,并且测试将失败。

直接比较.toBe('orange')仍然是可能的,但关于jest真正有用的是快照测试,因此您不需要重复逻辑和序列化/深度比较结构或jsx。

如果它是一个组件方法,您需要先渲染它,getInstance()然后调用它。

+0

嗯。我不断得到:TypeError:(0,_FirstComponent.sayMyName)不是函数 –

+0

哦,我试过用酶。现在与'react-test-renderer' –

+0

一起工作,你说[tag:jest] - not [tag:酶]。通常是:'const tree = renderer.create(); tree.getInstance()。方法()' –