javascript - 无法让 Jest 和 enzyme 从我的 App.js 渲染 div 测试

标签 javascript node.js reactjs unit-testing jestjs

我刚刚开始学习 Jest 和 enzyme 来测试 react 组件,我决定构建一个 MERN 应用程序来尝试一下。我多次尝试让它工作,但我肯定做错了什么。我试图将 div 宽度设置为 400。是否还有一种方法可以编写测试以确保每次都能渲染 div 内容?

这是我的 App.js 文件

import React, { Component } from 'react';
import gql from 'graphql-tag';
import { graphql, compose } from 'react-apollo';
import Paper from '@material-ui/core/Paper';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import ListItemText from '@material-ui/core/ListItemText';
import Checkbox from '@material-ui/core/Checkbox';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';
import Form from './Form'
// require enzyme
const Enzyme = require('enzyme');
const EnzymeAdapter = require('enzyme-adapter-react-16');
Enzyme.configure({ adapter: new EnzymeAdapter() });

const TodosQuery = gql`
  {
    todos {
      id
      text
      complete
    }
  }
`;

const CreateMutation = gql`
  mutation($text: String!) {
    createTodo(text: $text) {
      id
      text
      complete
    }
  }
`;

const UpdateMutation = gql`
  mutation($id: ID!, $complete: Boolean!) {
    updateTodo(id: $id, complete: $complete)
  }
`;

const RemoveMutation = gql`
  mutation($id: ID!) {
    removeTodo(id: $id)
  }
`;

class App extends Component {

  //arrow functioning binds to 'this'
  createTodo = async text => {
    //create todo
    await this.props.createTodo({
      variables: {
        text
      },
      update: (cache, {data: { createTodo }}) => {
        //read the data from our cache for this query
        const data = cache.readQuery({ query: TodosQuery });
        //query returns 'data' with 'todos', then do the front end changes needed (we also creating a copy of original array)
        data.todos.unshift(createTodo)
        //write data back to the cache
        cache.writeQuery({ query: TodosQuery, data });
      }
    });
  };

  updateTodo = async todo => {
    //update todo
    await this.props.updateTodo({
      variables: {
        id: todo.id,
        complete: !todo.complete
      },
      update: cache => {
        //read the data from our cache for this query
        const data = cache.readQuery({ query: TodosQuery });
        //query returns 'data' with 'todos', then do the front end changes needed
        data.todos = data.todos.map(x => x.id === todo.id ? { ...todo, complete: !todo.complete } : x );
        //write data back to the cache
        cache.writeQuery({ query: TodosQuery, data });
      }
    });
  };

  removeTodo = async todo => {
    //remove todo
    await this.props.removeTodo({
      variables: {
        id: todo.id
      },
      update: cache => {
        //read the data from our cache for this query
        const data = cache.readQuery({ query: TodosQuery });
        //query returns 'data' with 'todos', then do the front end changes needed (we also creating a copy of original array)
        data.todos = data.todos.filter(x => x.id !== todo.id)
        //write data back to the cache
        cache.writeQuery({ query: TodosQuery, data });
      }
    });
  };

  render() {
    console.log(this.props);
    const { data: { loading, todos }} = this.props;
    if (loading) {
      return null;
    }


    return (
      <div style={{ display: 'flex' }}>
        <div style={{ margin: "auto", width: 400 }}>
          <Paper elevation={1}>
            <Form submit={this.createTodo} />
            <List>
              {todos.map(todo => (
                <ListItem
                  key={todo.id}
                  role={undefined}
                  dense
                  button
                  onClick={() => this.updateTodo(todo)}
                >
                  <Checkbox
                  //checked can also be 'true' (everything checked) or false (nothing gets checked):
                    checked={todo.complete}
                    tabIndex={-1}
                    disableRipple
                  />
                  <ListItemText primary={todo.text} />
                  <ListItemSecondaryAction>
                    <IconButton onClick={() => this.removeTodo(todo)}>
                      <CloseIcon />
                    </IconButton>
                  </ListItemSecondaryAction>
                </ListItem>
              ))}
            </List>
          </Paper>
        </div>
      </div>
    )
  }
}

//here, 'compose' squishes queries together and wraps around the 'App'
//we also pass props to queries
export default compose(
  graphql(CreateMutation, {name: "createTodo"}),
  graphql(RemoveMutation, {name: "removeTodo"}),
  graphql(UpdateMutation, {name: "updateTodo"}),
  graphql(TodosQuery)
)(App);

这是我在 app.test.js 文件中编写的测试

import React from 'react';
import ReactDOM from 'react-dom';
import App from '../App';
//  shallow rendering to render a mock Dom
import { shallow, mount, render } from 'enzyme';



describe('div container', () => {
  it('div width is always 400', () => {
  expect(shallow(<App />).find('#style').width).toEqual(400)
})
})

我做错了什么或者应该做什么吗?

最佳答案

嗨,这对我有用,如下所示。我添加了 enzyme 适配器并配置。 This post和你的问题也很相似。

import React from 'react';
import ReactDOM from 'react-dom';
import App from '../App';
//  shallow rendering to render a mock Dom
import { shallow, mount, render } from 'enzyme';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });


describe('div container', () => {
  it('div width is always 400', () => {
    const divNode2 = shallow(<App />).find('div').at(1);
    expect(divNode2.prop('style').width).toEqual(400);
  });
});

关于javascript - 无法让 Jest 和 enzyme 从我的 App.js 渲染 div 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472591/

相关文章:

javascript - 无法在 JavaScript 中正确将 JSON 转换为 XML

javascript - Django 管理自定义小部件内联处理添加?

node.js - npm 代理设置转义 '\' 字符

node.js启动远程js文件

javascript - 在不刷新浏览器的情况下将数据传递给 View

javascript - 当我刷新时,Google 签名按钮消失 - React

javascript - 提交后重置输入字段

Javascript 错误 - 如果连接的字符串中有空格,则连接时出现未终止的字符串文字

javascript - multiCapabilities 和 jasmine 重点测试

reactjs - @测试库/ react : Clicking outside of component not working