首页 文章

单元测试使用Karma和Jasmine进行反应

提问于
浏览
4

我很反应,我使用React 14编写了一个没有任何转换器的代码 . 现在我想使用Karma-Jasmine进行单元测试,但似乎我的测试无法渲染应用程序 .

我有以下结构:

node_modules
MyApp/
    /js/ *.js
    /test/*.js
Karma.conf.js
package.json
index.html

我的index.html:

<html>
<div id="content"></div>
<script src="js/react-0.14.7.js"></script>
<script src="js/react-dom-0.14.7.js"></script>

<script src="js/App.js"></script>
<script src="js/main.js"></script>
<link rel="stylesheet" href="style.css">
</body>
</html>

我的main.js:

ReactDOM.render(React.createElement(App), document.getElementById('content'))

我的应用程序如下所示:

var h = React.createElement;

var Command = React.createClass({
   render: function(){
   return h(....)
  }
})

我的测试代码如下:

describe('App', function() {
beforeEach(function() {
fixture.load('index.htm');
});

beforeEach(function () {
ReactDOM.render(React.createElement(App),  document.getElementById('content'));
});

it('accepts elements', function() {
  document.getElementById('x').value = 1;
  document.getElementById('y').value = 2;
  document.getElementById('setbtn').click();
});

});

这是错误:

Uncaught ReferenceError: App is not defined
at main.js:2
(anonymous) @ main.js:2
debug.html:1 (WEB_PAGE context) Lazy require of app.binding did not set the binding field
.
.
.
ReferenceError: fixture is not defined
at UserContext.<anonymous> (main.test.js:6)

调试Karma显示我的文件已加载,因为我可以看到我的组件中的功能 . 我安装了Html2js并添加到我的Karma.conf.js中 . 我已经阅读了网上的大部分文件,但他们没有帮助 .

我究竟做错了什么?一世

2 回答

  • 5

    我们有许多测试工具来测试React应用程序 . 其中一些可能让初学者感到困惑,无法理解它们究竟用于什么 . 下面我澄清了不同的工具以及它们主要用于什么 .

    这是一个断言/期望库 . expect / should / assert是chai给出的函数 .

    摩卡/茉莉花

    这是一个测试运行器,用于运行测试并记录测试结果 .

    describe/it/beforeEach :mocha / jasmine的函数用于组织测试 .

    describe →描述一个功能

    it →指定满足某些条件 . 生活在描述中

    beforeEach →在开始之前进行设置测试

    测试的一个例子:

    describe "Strawberry"
      - it "is red"
        - expect(strawberry.color).to.be('red')
     - it "a type of fruit"
        - expect(strawberry.type).to.be('fruit)
    

    React的JavaScript测试实用程序,可以更轻松地断言,操作和遍历React组件 . 它模拟ReactDOM,以及像JQuery查找DOM的React组件 .

    它可用于浅渲染React组件,或检查组件是否有某些子组件或是否具有某些道具 .

    import MyComponent from ‘./MyComponent’;
    import Foo from ‘./Foo’;
    
    describe(‘<MyComponent />’, () => {
      it(‘renders three <Foo /> components’, () => {
        const wrapper = shallow(<MyComponent foo=’bar’ />);
        expect(wrapper.find(Foo)).to.have.length(3);
        expect(wrapper.props().foo).to.equal(‘bar’);
      });
    });
    
  • 3

    你在用js-fixtures吗?然后你需要写:

    fixtures.load('index.htm'); // <--- fixtureS not fixture!
    

相关问题