3
  • componentDidMount调用api的商店
  • api 是一个具有导出fetchVersionsRequest功能的模块
  • fetchVersionsRequest使用 Promise 调用 api 端点
  • all承诺解决后由商店更新
  • Mobx, via@observer将再次调用组件渲染,因为all已更新

请检查评论

主页组件

@inject('versionStore') @observer
export default class extends Component {
  componentDidMount() {
    const { fetch } = this.props.versionStore;
    fetch(); // Will call api.fetchVersionsRequest
  }

  render() {
    // all is an array updated after call api.fetchVersionsRequest resolved
    const { all } = this.props.versionStore; 
    // ...
    return {all.map(it => <p>{it.name}</p>)}
  }
}

如何测试组件是否正确呈现?
我想使用快照功能,给一个api返回的列表,组件应该是快照

我的测试主页组件

it('renders versions', function() {
  const versions = [
    { id: 1, name: 'version1' },
    { id: 2, name: 'version2' },
  ];

  api.fetchVersionsRequest = jest.fn(() => {
    return Promise.resolve(versions);
  });

  const wrapper = shallow(<Home {...this.minProps} />);
  expect(toJson(wrapper)).toMatchSnapshot(); // PROBLEM Snapshot does not contain any p element
}
4

2 回答 2

3

只是为了向您展示如何开玩笑地使用 Promise。你必须从你的测试中返回承诺,让 jest 知道它必须等待它。

it('renders versions', function() {
  const versions = [
    { id: 1, name: 'version1' },
    { id: 2, name: 'version2' },
  ];
  const p = Promise.resolve(versions);
  api.fetchVersionsRequest = jest.fn(() => {
    return p
  });

  const wrapper = shallow(<Home {...this.minProps} />);
  return p.then(()=>{
    expect(toJson(wrapper)).toMatchSnapshot(); 
  })

}

或者

it('renders versions', async function() {
  const versions = [
    { id: 1, name: 'version1' },
    { id: 2, name: 'version2' },
  ];
  const p = Promise.resolve(versions);
  api.fetchVersionsRequest = jest.fn(() => {
    return p
  });

  const wrapper = shallow(<Home {...this.minProps} />);
  a
  expect(toJson(wrapper)).toMatchSnapshot(); 

}

它在文档中进行了解释

于 2017-04-30T14:11:39.190 回答
0

而不是使用 jest.fn 来模拟来自 API 的数据。您可以通过使用wrapper.setProps直接设置道具来测试您的组件:

const wrapper = shallow(<Home {...this.minProps} />);
wrapper.setProps({
  versionStore: {
    all: versions
  }
});
expect(toJson(wrapper)).toMatchSnapshot();
于 2017-04-30T03:01:38.597 回答