使用业力和Jasmine的反应中组件的单元测试功能

时间:2017-02-20 06:36:49

标签: javascript unit-testing reactjs karma-jasmine

我有一个reactjs组件,该组件中有一个函数。我想为此编写单元测试用例。以下是我的样本单元测试用例。函数名称是getNewGroupName

describe("CreateGroupName component", () => {

      it("Correct Copy name should be generated for first copy", () => {
          component = ReactTestUtils.renderIntoDocument( < CreateGroupName reactor = {
              reactor
            } > < /CreateGroupName>);

            expect(component.getNewGroupName("SampleGroupName")).tobe("SampleGroupName - Copy(1)")
          });

      });

但是当我运行单元测试用例时,我收到的错误

TypeError:undefined不是构造函数(评估'e.getNewGroupName(“SampleGroupName”)')

使用调试器查看对象后,我只能看到此对象的下方属性。

enter image description here

我也尝试使用酶库编写上述测试。但是两人在结果中都给了我相同的对象。

 it("Correct Copy name should be generated for first copy", () => {
            const wrapper = enzyme.mount(<CreateGroupName reactor={reactor}></CreateGroupName>);
            const inst = wrapper.instance();
            expect(inst.getNewGroupName('SampleGroupName')).toBe("SampleGroupName - Copy(1)");
        });

这是我的组件

enter image description here

堆栈跟踪如下

"TypeError: t.getNewGroupName is not a function
    at Object.<anonymous> (http://localhost:9876/base/app/spec/webpack.loader.js:96:18873)
    at attemptSync (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1886:24)
    at QueueRunner.run (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1874:9)
    at QueueRunner.execute (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1859:10)
    at Spec.queueRunnerFactory (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:697:35)
    at Spec.execute (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:359:10)
    at Object.fn (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:2479:37)
    at attemptAsync (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1916:24)
    at QueueRunner.run (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1871:9)
    at http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1898:16"

1 个答案:

答案 0 :(得分:0)

ReactTestUtils.renderIntoDocument()呈现一个DOM节点,表示组件渲染后的输出。见https://facebook.github.io/react/docs/test-utils.html#renderintodocument

看起来您正在尝试调用getNewGroupName(),它是React组件上的函数,而不是渲染DOM节点上的方法。