如何用玩笑模拟和测试链接函数?

时间:2019-08-30 02:24:10

标签: jestjs react-testing-library

我的组件useEffect挂钩中有此功能链。 我将响应/数据设置为组件状态,以便可以在组件中呈现数据。

client
  .items()
  .type("client")
  .toObservable()
  .subscribe(response => {
    setState(response)
  })

如何模拟该函数并在组件在测试中呈现之前调用它?我正在使用测试库/反应。

响应是 {items: [{},...]}, somethingElse: {}

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,这里是解决方案。

client.ts,模拟真实的第三方模块

const client = {
  items: () => {
    return client;
  },
  type: (name: string) => {
    return client;
  },
  toObservable: () => {
    return client;
  },
  subscribe: handler => {
    handler();
    return client;
  }
};

export { client };

在react组件中使用client.ts模块:

class Component {
  private props;
  constructor(props) {
    this.props = props;
  }
  public componentDidMount() {
    this.props.client
      .items()
      .type('client')
      .toObservable()
      .subscribe(response => {
        this.setState(response);
      });
  }
  private setState(state) {
    console.log(state);
  }
}

export { Component };

单元测试,真实的client.ts模块的模拟链方法,将模拟的client模块注入到您的组件中。

import { Component } from './';

const mockClient = {
  items: jest.fn().mockReturnThis(),
  type: jest.fn().mockReturnThis(),
  toObservable: jest.fn().mockReturnThis(),
  subscribe: jest.fn().mockReturnThis()
};

const mockProps = {
  client: mockClient
};

const component = new Component(mockProps);

describe('Component', () => {
  describe('#componentDidMount', () => {
    it('should mount the component and set state correctly', () => {
      const mockedResponse = { items: [{}], somethingElse: {} };
      mockClient.subscribe.mockImplementationOnce(handler => handler(mockedResponse));
      // tslint:disable-next-line: no-string-literal
      component['setState'] = jest.fn();
      component.componentDidMount();
      expect(mockClient.items().type).toBeCalledWith('client');
      // tslint:disable-next-line: no-string-literal
      expect(component['setState']).toBeCalledWith(mockedResponse);
    });
  });
});

单元测试结果:

 PASS  src/mock-function/57719741/index.spec.ts
  Component
    #componentDidMount
      ✓ should mount the component and set state correctly (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.542s, estimated 2s
相关问题