【问题标题】:Jest coverage still flagging line after applying test应用测试后,Jest 覆盖率仍在标记行
【发布时间】:2018-10-08 16:17:45
【问题描述】:

我正在测试的 React 组件中有以下功能。

renderLoginLink(caption) {
    return (
      <a href="#" id="lnkAuthenticateWithGoogle" onClick={() => this.props.actions.authenticateWithGoogle()}>
       {caption}
      </a>
    );
  }

当我运行 jest --coverage 时,该功能被标记。我已经为通过的函数编写了以下测试。

describe('Login', () => {
    it('calls renderLoginLink()', () => {
        const actions = {
            authenticateWithGoogle: jest.fn()
        }
        const expectedNode = <a href="#" id="lnkAuthenticateWithGoogle" onClick={() => actions}>testCaption</a>

        let node = document.createElement('div');
        let instance = ReactDOM.render(<Login {...initialState} />, node);
        expect(JSON.stringify(instance.renderLoginLink("testCaption"))).toEqual(JSON.stringify(expectedNode));
    });
});

我不确定我遗漏了什么,或者我可以编写什么其他测试来满足开玩笑的覆盖率。

【问题讨论】:

  • 运行jest --clearCache 是否先修复它?

标签: reactjs jestjs enzyme


【解决方案1】:

尝试使用酶中的shallowsimulate

function setup() {
  const props = {
    actions: {
      authenticateWithGoogle: jest.fn(),
    },
  };

  return { props };
}

describe('Login', () => {
  const props = setup();
  const component = shallow(<Login {...props} />);

  it('calls renderLoginLink() ', () => {
    const loginLink = component.find('lnkAuthenticateWithGoogle');
    loginLink.simulate('click');
    expect(props.actions.authenticateWithGoogle).toBeCalled();
  });
});

【讨论】:

    【解决方案2】:

    你开玩笑说 onclick 处理程序应该等于这个:

    () => actions
    

    这是一个返回一个对象并且什么都不做的函数。

    相反,我会使用 shallow() 渲染组件,将 authenticateWithGoogle 函数作为 jest 存根传递,并验证单击 &lt;a&gt; 会调用模拟。

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 2019-04-08
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多