【问题标题】:Enzyme: "Error: Method “text” is meant to be run on 1 node. 0 found instead."酶:“错误:方法“文本”应在 1 个节点上运行。但找到了 0 个节点。”
【发布时间】:2021-09-13 22:45:29
【问题描述】:

我也在尝试使用 Enzyme 将单元测试添加到我一直在从事的项目中。我已经能够设置一个基本测试,但是,当我尝试运行它时,我收到以下错误“方法“文本”应该在 1 个节点上运行。找到了 0。”

我一直在浏览各种在线教程,以及类似问题的 SO 答案,但我找不到任何有用的东西。我也试过 console.log-ing 包装器,它返回:

<Connect(withRouter(WithStyles(SignIn))) >

正在测试的代码;

class SignIn extends Component {

//Removed unnecessary code for expediency

  render() {
    const { classes, loading } = this.props;
    const {
      values,
      touched,
      errors,
      isValid,
    } = this.state;

    const hasError = field => !!(touched[field] && errors[field]);
    const { store } = configureStore();

    return (
      <Provider store={store}>
        <div className={classes.root}>
          <Grid
            className={classes.grid}
            container
          >
            <Grid
              className={classes.quoteWrapper}
              item
              lg={5}
            >
              <div className={classes.quote}>
                <div className={classes.quoteInner}>
                  <Typography
                    className={classes.quoteText}
                    variant="h1"
                  >
                    We work with your business to provide a range of innovative
                    and bespoke software solutions.
                  </Typography>
                </div>
              </div>
            </Grid>
            <Grid
              className={classes.content}
              item
              lg={7}
              xs={12}
            >
              <div className={classes.content}>
                <div className={classes.contentBody}>
                  <form className={classes.form}>


                     <p>
                      <Typography
                        className={classes.title}
                        variant="h2"
                      >
                        Sign in
                      </Typography>
                    </p>



                    <div className={classes.fields}>
                      <TextField
                        className={classes.textField}
                        error={hasError('username')}
                        helperText={
                          hasError('username') ? errors.username[0] : null
                        }
                        label="User name"
                        name="username"
                        onChange={event =>
                          this.handleFieldChange('username', event.target.value)
                        }
                        onKeyPress={this.handleKeyPress}
                        type="text"
                        value={values.username}
                        variant="outlined"
                      />
                      <TextField
                        className={classes.textField}
                        error={hasError('password')}
                        helperText={
                          hasError('password') ? errors.password[0] : null
                        }
                        label="Password"
                        name="password"
                        onChange={event =>
                          this.handleFieldChange('password', event.target.value)
                        }
                        onKeyPress={this.handleKeyPress}
                        type="password"
                        value={values.password}
                        variant="outlined"
                      />
                    </div>
                    {loading ? (
                      <CircularProgress className={classes.progress}/>
                    ) : (
                      <Button
                        className={classes.signInButton}
                        color="primary"
                        disabled={!isValid}
                        onClick={this.handleSignIn}
                        size="large"
                        variant="contained"
                      >
                        Sign in now
                      </Button>
                    )}
                    <Typography
                      className={classes.resetPassword}
                      variant="body1"
                    >
                      Have you forgotten your password?{' '}
                      <Link
                        className={classes.resetPasswordURL}
                        to="/reset-password"
                      >
                        Reset it
                      </Link>
                    </Typography>
                  </form>
                </div>
              </div>
            </Grid>
          </Grid>
        </div>
      </Provider>
    );
  }
}

SignIn.propTypes = {
  className: PropTypes.string,
  classes: PropTypes.object.isRequired,
  dispatch: PropTypes.func.isRequired,
  history: PropTypes.object.isRequired,
  loading: PropTypes.bool.isRequired,
  user: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  loading: state.authReducer.loadingKeys.includes(dataConstants.loading.main),
  user: state.authReducer.user
});

export default connect(mapStateToProps)(compose(
  withRouter,
  withStyles(styles)
)(SignIn));

这是我的测试:

describe('SignIn component', () => {
  it('starts with a count of 0', () => {
    const wrapper = shallow(
      <Provider store={store}>
        <SignIn/>;
      </Provider>
    ).dive();
    let wrapperDebug = wrapper.debug();
    console.log(wrapperDebug);
    const text = wrapper.find('p').text();
    expect(text).toEqual('Sign in');

  });

});

测试应该找到被 p 包围的字体(我在代码的两边都留了几行以突出显示该区域),并将找到的文本与预期值进行比较。提前感谢您的帮助!

【问题讨论】:

  • 尝试使用mount 而不是shallow,这样它就可以呈现完整的组件树。
  • 得到一个新的错误Error: Uncaught [Error: Invariant failed: You should not use &lt;withRouter(WithStyles(SignIn)) /&gt; outside a &lt;Router&gt;]
  • 看起来您的&lt;p&gt; 标签包含排版,而排版又包含一个文本。你试过wrapper.find('p').first().find('Typography').text() 吗?

标签: reactjs redux jestjs enzyme


【解决方案1】:

要解决这个问题:错误:未捕获 [错误:不变式失败:您不应该在 ] 之外使用 。正如在较早的帖子中所说,您应该使用 mount() 来渲染所有组件树。另外,使用 react-router-dom 来包装你的组件。这将替换组件以进行测试。

希望对您有所帮助:https://reactrouter.com/web/api/MemoryRouter

【讨论】:

    猜你喜欢
    • 2017-08-21
    • 2021-03-10
    • 2019-07-14
    • 1970-01-01
    • 2019-07-20
    • 2017-02-02
    • 2016-09-19
    • 2021-03-09
    • 1970-01-01
    相关资源
    最近更新 更多