(反应组件测试)如何使用jasmine

时间:2018-02-11 08:55:19

标签: reactjs unit-testing testing jasmine

我正在为React Component编写单元测试。如何编写单元测试来检查来自不同模块的函数是否在jasmine中的componentDidMount中被调用。 这是我的组件:

import {differentModuleFunc} from "someModule";
class MyComponent extends React.Component {

    componentDidMount() {
        differentModuleFunc();
    }

    render() {
        return 
            <div>
               TestDiv
            </div>;
    }
 }

我对组件的单元测试如下:

describe("MyComponent", () => {
    it("differentModuleFunc should have been called", (done) => {
        const spy = spyOn(MyComponent, "differentModuleFunc");
        myComponentDiv = TestUtils.renderIntoDocument(<MyComponent/>);
        expect(myComponentDiv).toBeDefined();
        expect(spy).toHaveBeenCalled();
    });
});

感谢。

1 个答案:

答案 0 :(得分:0)

您可以模拟该功能,然后断言呼叫计数。使用您的示例,您可以执行以下操作:

import {differentModuleFunc} from "someModule";
class MyComponent extends React.Component {

    componentDidMount() {
        differentModuleFunc();
    }

    render() {
        return 
            <div>
               TestDiv
            </div>;
    }
 }

您在测试中导入“someModule”,模拟它然后断言呼叫计数。

import {differentModuleFunc} from "someModule"; // import the function

jest.mock('someModule', () => ({ differentModuleFunc: jest.fn() })) // mocks the function

describe("MyComponent", () => {
    it("differentModuleFunc should have been called", (done) => {
        const spy = spyOn(MyComponent, "differentModuleFunc");
        myComponentDiv = TestUtils.renderIntoDocument(<MyComponent/>);
        expect(myComponentDiv).toBeDefined();
        expect(spy).toHaveBeenCalled();
        expect(differentModuleFunc.mock.calls.length).toBe(1) // assert call count
    });
});