如何在Component内部使用Enzyme + Mocha方法调用

问题描述 投票:1回答:1

无法弄清楚如何使用酶+ mocha + sinon测试组分方法。我想测试组件是否在按钮单击时调用方法loadPosts。

import React from 'react';
import { configure, mount} from 'enzyme';
import { expect } from 'chai';
import Adapter from 'enzyme-adapter-react-16';
import { Posts } from '../Components/Posts';
import sinon from 'sinon';
configure({ adapter: new Adapter() });

describe('Posts', () => {

    let wrapper;
    let inst;

    beforeEach(() => {
        wrapper = mount(<Posts />);
        inst = wrapper.instance();
        sinon.spy(inst, 'loadPosts');
        wrapper.find('button').simulate('click');
    });

    it('should load posts on button click', () => {
        wrapper.update();
        expect(inst.loadPosts).to.have.property('callCount', 1);
    });

    it('should set `loading` to true', () => {
        expect(wrapper.state('loading')).to.equal(true);
    });
});

这是我的组成部分:

import React, {Component} from 'react';
import axios from 'axios';

export class Posts extends Component {
    
    state = {
        posts: null,
        loading: false
    }

    componentDidMount() {}

    loadPosts = () => {
        this.setState({loading: true}, () => {
            axios.get('https://jsonplaceholder.typicode.com/todos')
            .then( d => this.setState({
                posts: d.data
            }));    
        });
    }

    render() {
        return (<div>
                <h4>I am posts</h4>
                <button onClick= {this.loadPosts}>Load posts</button>
            </div>);
    }
    
}

但我的测试失败并出现错误:异常错误:预期[Function]使属性'callCount'为1但得到0

reactjs mocha enzyme sinon
1个回答
0
投票

你的onClickbutton直接绑定到组件渲染时的this.loadPosts

当你用间谍取代loadPosts时,它对当前渲染的button没有任何影响,所以onClick不会打电话给你的间谍。


修复它的两个选项是使用箭头函数调用this.loadPosts,如下所示:

<button onClick={() => this.loadPosts()}>Load posts</button>

...所以当onClick被调用时,它会调用当前设置的this.loadPosts

另一个选择是在你创建间谍之后强制重新渲染,所以onClick被绑定到你的间谍而不是原始的功能。

© www.soinside.com 2019 - 2024. All rights reserved.