繁体   English   中英

用Mocha和Chai测试React

[英]Testing React with Mocha and Chai

我有一个简单的JavaScript计算器应用程序,我想使用Mocha和Chai学习测试驱动的开发。

Calculator_app.js

class calculator_app extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        formdata: ''
      };

      this._onAdd  = this._onAdd.bind(this);
      this._onSubtract  = this._onSubtract.bind(this);
      this._onMultiply  = this._onMultiply.bind(this);
      this._onDivide = this._onDivide.bind(this);
      this._onClear = this._onClear.bind(this);
      this.sayHello = this.sayHello.bind(this);
    }

    sayHello() {
        return 'hello';
    }

    render() {

        return (
            <App>
                {infoform}
                <MyHeader/>
                <Section>
                <Box colorIndex="brand">
                    <Heading style={{color: '#ffffff'}} id='header1'>Frosties Calculator</Heading>
                </Box>
                    <Box alignSelf="center" />
                    <Box>
                        <Box>
                            <Header size="small" colorIndex="grey-2" id='header2' />
                            <Box colorIndex="light-2" pad={{ horizontal: 'medium', vertical: 'medium', between: 'medium' }}>
                                <Box colorIndex="light-1" pad="large" separator="all">
                                    <Heading strong={true} id='header3'>Calculator</Heading>    
                                    <Paragraph>
                                        Sample code to display a calculator. 
                                    </Paragraph>                                
                                </Box>
                            </Box>
                        </Box>
                    </Box>
                </Section>
                <MyFooter/>
            </App>
        );
    }
}

export default calculator_app;

Calculator_app.test.js

const assert = require('chai').assert;
const calculator = require('../src/js/components/calculator_app.js');

describe('calculator', function () {
  describe('sayHello()', function () {

        it('app should return hello', function () {
          let result = calculator.sayHello();
          assert.equal(result, 'hello');
        });
    });
});

当我尝试运行Calculator_app.test来检查sayHello函数的返回值时,出现以下错误:

0传递(107毫秒)1失败1)计算器sayHello()应用应返回问候:TypeError:Calculator.sayHello不是上下文中的函数。 (C:/Users/maherni/Desktop/Projects/JavaScript/calculator_app/test/calculator_app.test.js:8:29)

有人可以告诉我我做错了什么吗,我已经检查了测试文件的路径和格式

看起来您尝试调用方法sayHello而不实例化calculator React Component类。 尝试这个:

    it('app should return hello', function () {
      let result = new calculator().sayHello();
      assert.equal(result, 'hello');
    });

如果要测试render方法的行为,您确实应该看看Paul Fitzgerald建议的Enzyme

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM