如何使用酶作为instance()测试功能组件内部的方法,对于浅层包装返回null?

问题描述 投票:0回答:1

假设我有一个像这样的简单组件。

import React, { useState } from "react";

const Counter = () => {
  const [counter, setCounter] = useState(0);
  const incCounter = () => {
    setCounter(counter + 1);
  };
  return (
    <>
      <p>Counter value is: {counter}</p>
      <button className="increment" onClick={incCounter}>
        Up
      </button>
    </>
  );
};
export default Counter;

我想用玩笑和酶写测试用例。但是counter.instance()始终返回null。任何帮助将不胜感激。

import React from "react";
import Counter from "../components/Counter";
import {
  mount,
  shallow
} from "./enzyme";

describe("Counter", () => {
  let counter;
  beforeEach(() => {
    counter = shallow( < Counter / > );
  })

  it("calls incCounter function when button is clicked", () => {
    console.log(counter)
    counter.instance().incCounter = jest.fn();
    const incButton = counter.find("button");
    incButton.simulate("click");
    expect(counter.incCounter).toBeCalled();

  })

});
javascript reactjs jestjs enzyme react-functional-component
1个回答
0
投票

来自此文档:https://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html

注意:只能在也是根实例的包装实例上调用。对于React 16及更高版本,instance()对于无状态功能组件返回null。

测试组件行为,而不是实施细节。

例如

index.jsx

import React, { useState } from 'react';

const Counter = () => {
  const [counter, setCounter] = useState(0);
  const incCounter = () => {
    setCounter(counter + 1);
  };
  return (
    <>
      <p>Counter value is: {counter}</p>
      <button className="increment" onClick={incCounter}>
        Up
      </button>
    </>
  );
};
export default Counter;

index.spec.jsx

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

describe('Counter', () => {
  let counter;
  beforeEach(() => {
    counter = shallow(<Counter />);
  });

  it('calls incCounter function when button is clicked', () => {
    expect(counter.find('p').text()).toBe('Counter value is: 0');
    const incButton = counter.find('button');
    incButton.simulate('click');
    expect(counter.find('p').text()).toBe('Counter value is: 1');
  });
});

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

 PASS  src/stackoverflow/59475724/index.spec.jsx (10.045s)
  Counter
    ✓ calls incCounter function when button is clicked (17ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.jsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.697s

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

© www.soinside.com 2019 - 2024. All rights reserved.