简体   繁体   English

为什么我无法使用酶检测按钮元素?

[英]Why can't I detect the button element using enzyme?

I used npm install --save enzyme react-test-renderer enzyme-adapter-react-16 to start things off. 我使用npm install --save enzyme react-test-renderer enzyme-adapter-react-16开始。 I wrote the code below then ran npm test to get the output I got in Terminal . 我在下面编写了代码,然后运行npm test以获取在Terminal获得的输出。

What am I doing wrong and how can I fix it? 我在做什么错,我该如何解决?

Here's CheckoutButton.js : 这是CheckoutButton.js

import React from 'react';
import classes from './CheckoutButton.css';

const button = (props) => (
    <button className={classes.Button} id="test" onClick={props.clicked}>Checkout</button>
);

export default button;

Here's CheckoutButton.test.js : 这是CheckoutButton.test.js

import React from 'react';

import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import CheckoutButton from './CheckoutButton';

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

describe('<CheckoutButton />', () => {
    it('should logout upon clicking the button', () => {
        const wrapper = shallow(<CheckoutButton/>);
        expect(wrapper.find("button")).toHaveLength(1);
    });
});

Here's what I get in the Terminal: 这是我在终端机中得到的:

Test Suites: 2 failed, 2 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.572s, estimated 3s
Ran all test suites related to changed files.

Your adapter config doesn't seem to be correct. 您的适配器配置似乎不正确。

Try: 尝试:

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

instead of: 代替:

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

Because it's in your root while you are trying to find it in children. 因为当您试图在儿童中找到它时,它就在您的根中。 Your expect should be expect(wrapper.type()).toEqual('button'); 您的期望应该是expect(wrapper.type()).toEqual('button');

In CheckoutButton.js update your code to: CheckoutButton.js将代码更新为:

import React from 'react';
import classes from './CheckoutButton.css';

const CheckoutButton = (props) => (
    <button className={classes.Button} id="test" onClick={props.clicked}>Checkout</button>
);

export default CheckoutButton;

As per React component naming convention, you should always name your component in PascalCase. 根据React组件的命名约定,您应该始终在PascalCase中命名您的组件。

Component name should always start from Capital letter. 组件名称应始终以大写字母开头。 Making this change will pass the test case. 进行此更改将通过测试用例。

More detail cann be find here: Component Naming Convention . 无法在此处找到更多详细信息: 组件命名约定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM