小编Alb*_*ivé的帖子

如何正确测试React Dropzone onDrop方法

我正在测试React Dropzone,我需要检查onDrop函数.此函数有两个参数(acceptedFiles和rejectedFiles).我在嘲笑这样的文件:

let image = {
  name: 'cat.jpg',
  size: 1000,
  type: 'image/jpeg'
};
Run Code Online (Sandbox Code Playgroud)

然后在我的测试中,我这样做:

it('should call handleOnDrop with more than 5 acceptedFiles', () => {
    const wrapper = mount(mockComponent());

    for (let index = 0; index < 5; index++) {
      images.push(image);
    }

    wrapper.find(Dropzone).simulate('drop', { dataTransfer: { files: images } });

    expect(setUserNotificationsSpy).toHaveBeenCalledTimes(1);
});
Run Code Online (Sandbox Code Playgroud)

这是我的onDrop函数:

const handleOnDrop = (acceptedFiles, rejectedFiles) => {
    if (rejectedFiles && rejectedFiles.length) {
      checkMaxFile(rejectedFiles, maxSize) && setUserNotifications('error_big_image');
    }

    acceptedFiles && acceptedFiles.length <= maxFiles ? onDrop(acceptedFiles) : setUserNotifications('more_than_5'); …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs jestjs react-dropzone

10
推荐指数
2
解决办法
2491
查看次数

如何测试 React Loadable 组件

我有这个组件:

import React from 'react';

const UploadAsync = Loadable({
  loader: () => import('components/Upload'),
  loading: () => <LoadingComponent full />
});

const Component = () => {
  return <UploadAsync />
}

export default Component
Run Code Online (Sandbox Code Playgroud)

和测试:

import React from 'react';
import Component from './index';

describe('Component', () => {
  it('should render correctly with upload component', () => {
    const tree = create(<Component />).toJSON();

    expect(tree).toMatchSnapshot();
  });
});
Run Code Online (Sandbox Code Playgroud)

如何在快照中看到上传组件而不是加载组件?

exports[`Content should render correctly with form component 1`] = `
  <div>
    <Loading
      full={true}
    />
  </div>
`; …
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs enzyme react-loadable

7
推荐指数
2
解决办法
6774
查看次数

如何在 Jest 快照中使用 Enzyme Shallow

我正在尝试使用来自酶的浅层,并同时使用来自开玩笑的快照

我面临的问题是我需要使用setState()from从状态中更改某些内容,然后将结果与快照进行匹配。

查看我的组件的代码:

....

getPrevProduct = () => {
  const key = this.state.indexCurrent > 0 &&
   this.productsKeys[this.state.indexCurrent - 1];

  let product = null;

  if (key) {
    product = this.props.products[key];
  }

  return product;
}

renderPrev = () => this.getPrevProduct() && <PrevButton />;

render() {
  return (
    <div>
      ...
      {this.renderPrev()}
      ...
    <div>
  )
}
Run Code Online (Sandbox Code Playgroud)

前面的代码检查从 currentIndex 中的 props 传递的产品是否存在。

这就是为什么我需要 Enzyme 来改变状态。然后,如果匹配,<PrevButton />则必须呈现。

这个测试是当我想将组件与快照匹配时:

const nextProps = {
  products: { …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs jestjs enzyme

5
推荐指数
3
解决办法
3789
查看次数

如何使用Jact与React和Webpack

我试图配置Jest与React和Webpack一起工作.通过我使用Webpack别名和ES6模块导出的方式,我在配置它时遇到了很大的问题.

由于没有其他问题对我有用,我想向您展示我能够将Jest与ReactJs和Webpack一起使用.

facebook ecmascript-6 reactjs webpack jestjs

4
推荐指数
1
解决办法
3810
查看次数

如何使用Jest和Enzyme测试getDerivedStateFromProps

我有一个使用getDerivedStateFromProps新生命周期的简单代码:

static getDerivedStateFromProps(nextProps: Props, prevState: State) {
  if (nextProps.value !== prevState.value) {
    console.log('hello');
    return {
      value: nextProps.value
    };
  }

  return null;
}
Run Code Online (Sandbox Code Playgroud)

这是测试:

it('should call getDerivedStateFromProps', () => {
  const instance = shallow(mockComponent());

  instance.setProps({ value: 'test2' });

  expect(instance.state.value).toEqual('test2');
});
Run Code Online (Sandbox Code Playgroud)

但是我有这个错误,但是我知道由于console.log()正在调用。

Expected value to equal:
  "test2"
Received:
  undefined
Run Code Online (Sandbox Code Playgroud)

如何正确测试getDerivedStateFromProps

我正在使用:

react: 16.4
react-Dom: 16.4
enzyme-adapter-react-16: 1.1.1
react-test-renderer: 16.4.1
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs jestjs enzyme

4
推荐指数
2
解决办法
2925
查看次数

4
推荐指数
2
解决办法
781
查看次数

如何使用Jest和新的React lazy 16.6 API测试快照

我必须使用新的React lazyAPI(16.6)导入组件.

import React, {PureComponent, lazy} from 'react';

const Component1 = lazy(() => import('./Component1'));
const Component2 = lazy(() => import('./Component2'));

class CustomComponent extends PureComponent {
  ...
  render() {

  return (
    <div>
      <Component1 />
      <Component2 />
    </div>
  );
 }
}
Run Code Online (Sandbox Code Playgroud)

在我的测试中,我正在做这个组件的快照.这是一个非常简单的测试:

import { create } from 'react-test-renderer';

const tree = await create(<CustomComponent />).toJSON();

expect(tree).toMatchSnapshot();
Run Code Online (Sandbox Code Playgroud)

在日志中,测试失败并显示以下错误:

A React component suspended while rendering, but no fallback UI was specified.

Add a <Suspense fallback=...> component higher in the tree to provide a loading …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs jestjs react-test-renderer

4
推荐指数
2
解决办法
3929
查看次数

使用Jest手动模拟React-Intl进行快照测试

我一直在用Jest努力模拟React-Intl库,因为在运行测试时遇到此错误:

Invariant Violation: [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.
Run Code Online (Sandbox Code Playgroud)

该库的文档说,我们必须在根项目中创建一个名为的文件夹__Mocks__,然后添加此文件:

// ./__mocks__/react-intl.js
import React from 'react';
const Intl = require.requireActual('react-intl');

// Here goes intl context injected into component, feel free to extend
const intl = {
  formatMessage: ({defaultMessage}) => defaultMessage
};

Intl.injectIntl = (Node) => (props) => <Node {...props} intl={intl}/>;

module.exports = Intl;
Run Code Online (Sandbox Code Playgroud)

但是什么也没发生。

javascript unit-testing reactjs jestjs react-intl

3
推荐指数
1
解决办法
2946
查看次数

如何用jest模拟回调函数

我正试图用开玩笑模拟一个自定义函数,但我遇到了问题.

这是我的功能:

export const resizeImage = (file, fileName, callback) => {
  const MAX_WIDTH = avatarImage.maxWidth;
  const MAX_HEIGHT = avatarImage.maxHeight;
  const img = document.createElement('img');
  img.src = window.URL.createObjectURL(file);
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');

  img.onload = () => {
    const sizes = internalResizeImage(img, MAX_WIDTH, MAX_HEIGHT);

    canvas.width = sizes.width;
    canvas.height = sizes.height;
    ctx.drawImage(img, 0, 0, sizes.width, sizes.height);
    return callback(dataURItoFile(canvas.toDataURL(), fileName));
  };
};
Run Code Online (Sandbox Code Playgroud)

我打电话是这样的:

resizeImage(acceptedFiles[0], this.props.user.id, (res) => {
  //dostuff
});
Run Code Online (Sandbox Code Playgroud)

在我的测试中,我嘲笑它:

let mockResizeImage = jest.fn();

jest.mock('../../utilities/imageUtils', () => ({
  resizeImage: () …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing callback jestjs

3
推荐指数
1
解决办法
1万
查看次数

Jest 测试文件中的模拟文档

我在 React 组件中有这个方法,可以在 componentDidMount 时加载Google Recaptcha API

loadCaptcha = () => {
  ((d, s, id) => {
    const element = d.getElementsByTagName(s)[0];
    const fjs = element;
    let js = element;
    if (d.getElementById(id)) {
      return;
    }
    js = d.createElement(s);
    js.id = id;
    js.src = '//google.com/recaptcha/api.js';
    fjs.parentNode.insertBefore(js, fjs);
  })(document, 'script', 'google-recaptcha');
};
Run Code Online (Sandbox Code Playgroud)

document我在 Jest 测试文件中进行模拟时遇到问题,因为d只有.Document { location: [Getter/Setter] }undefined

我尝试添加setupFilesJest 配置,正如其他人在另一个问题中所说

"setupFiles": ["<rootDir>/__mocks__/documentMock.js"]

documentMock.js:

Object.defineProperty(document, 'currentScript', {
  value: document.createElement('script'),
});
Run Code Online (Sandbox Code Playgroud)

但没有运气。有人解决了吗?

还尝试过这个: …

javascript recaptcha reactjs jestjs

2
推荐指数
1
解决办法
2万
查看次数

如何在 setupTests 中覆盖 Jest 模拟

我添加jest.mock('./Component')进来是setupTests.js因为我不想在每个有Component.

但现在,当我想测试时Component,它被嘲笑了。

我如何覆盖或重置它,以获得原始的Component

到目前为止我已经尝试过:

  • jest.unmock(模块名称)
  • jest.dontMock(模块名称)
  • jest.clearAllMocks()
  • jest.resetAllMocks()
  • jest.restoreAllMocks()
  • jest.resetModules()

和:

jest.mock('./index', () => ({
  Component: 'Component'
}));
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing jestjs

2
推荐指数
1
解决办法
3584
查看次数