如何使用Jest和酶

时间:2019-12-11 08:32:18

标签: node.js reactjs unit-testing jestjs enzyme

我有一个TestContainer

class TestContainer extends Component {
  constructor(props) {
    super(props)
    this.myValue = 5;
  }
}

并且我正在使用带有酶的Jest进行测试,我想测试myValue成功呈现时将TestContainer设置为5。我的测试代码:

describe("TestContainer tests", () => {
  const wrapper = shallow(<TestContainer />);

  it("TestContainer should start", () => {
    expect(wrapper.exists()).toBe(true);
    // I dont know how to get the value of myValue.
  });
});

任何人都可以帮忙。

1 个答案:

答案 0 :(得分:1)

您可以使用.instance() => ReactComponent获取react组件实例并声明属性MapScreen的值。

例如

myValue

index.tsx

import { Component } from 'react'; export class TestContainer extends Component { public myValue = -1; constructor(props) { super(props); this.myValue = 5; } public render() { return null; } }

index.spec.tsx

覆盖率100%的单元测试结果:

import React from 'react';
import { TestContainer } from './';
import { shallow } from 'enzyme';

describe('TestContainer', () => {
  it('should pass', () => {
    const wrapper = shallow(<TestContainer></TestContainer>);
    const instance = wrapper.instance();
    expect(wrapper.exists()).toBeTruthy();
    expect(instance['myValue']).toBe(5);
  });
});

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59281612