2016-03-01 65 views
15

我正在使用摩卡酵素创建反应组分的单元测试。以下是一个示例组件。摩卡,酵素:单元测试使用酶的反应组分中的自定义功能

Foo.js

class Foo extends React.Component { 
    customFunction=() => { 
    } 

    render() { 
     return (<div className={this.props.name}/>); 
    } 
} 

这里是测试文件。

富-Test.js

import React from 'react'; 
import { expect } from 'chai'; 
import { shallow, mount, render } from 'enzyme'; 
import Foo from '../src/Foo'; 

describe("A suite", function() { 
    it("contains spec with an expectation", function() { 
     expect(shallow(<Foo />).contains(<div className="foo" />)).to.equal(true); 
    }); 

    it("contains spec with an expectation", function() { 
     expect(shallow(<Foo />).is('.foo')).to.equal(true); 
    }); 
}); 

一切都很好。但我不知道如何进行单元测试customFunction在Foo.js当我们使用酶

回答

26

最好的回答这个问题实际上取决于它是什么,customFunction其实就是做...

你可以这样调用该函数:

wrapper.instance().customFunction('foo', 'bar'); 

如果它是设置在实例本身状态的功能,从而影响渲染输出的样子,你可能需要调用.update()以及

wrapper.instance().customFunction('foo', 'bar'); // uses setState internally 
wrapper.update(); // updates render tree 
// do assertions on the rendered output 
+0

是的。那工作。谢谢.. – pnsrinivasreddy

+0

但是有一点,这个instace()方法在全局范围内有任何问题。呈现的组件具有localStorage。在测试控制台时抛出ReferenceError:localStorage没有定义。 – pnsrinivasreddy

+1

不知道为什么这不被标记为答案。 –