使用 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 函数上的 return 时,出现以下错误:

0 passing (107ms) 1 failing 1) calculator sayHello() app should return hello: TypeError: calculator.sayHello is not a function at Context. (C:/Users/maherni/Desktop/Projects/JavaScript/calculator_app/test/calculator_app.test.js:8:29)

谁能告诉我我做错了什么,我已经检查了我的测试文件的路径和结构

您似乎试图在未实例化 calculator React 组件 class 的情况下调用方法 sayHello。试试这个:

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

如果你想测试 render 方法的行为,你确实应该看看 Enzyme, as Paul Fitzgerald 建议。