我正在使用反应,开玩笑和酶与不可变的 . 我正在尝试安装从API获取数据的组件,我遇到了一些困难 .

// FooListContainer.jsx

export default class FooListContainer extends Component {
    constructor(props) {
        super(props);

        this.state = {
           foos: List()
        }
    }

    componetWillMount() { 
        manager.bringFooList()
        .then(lst => this.setState({ foos: fromJS(lst) }))
        .done();
    }

    render() {
        return <FooList foos={this.state.foos} />
    }
}

这是ui组件,它所做的只是接收列表并映射它们

// FooList.jsx

export default class FooList extends Component {
    render() {
        return (
           <div>
               {this.props.foos.map(item => <div>{item}</div>)}
           </div>
        );
    }
}

现在我想测试从FooListContainter中的fetch接收的数据是否正确传递给FooList .

// FooListContainer.test.jsx

describe('rendering', () => {
    it('Should passed the data from the fetch to the FooList', () => {
        const response = ['1', '2', '3'];

        manager.bringFooList = jest.fn(() => {
           return new Promise(resolve => {
               return resolve(response);
           });
        })

        const wrapper = mount(<FooListContainer />);

        const fooList = wrapper.find(FooList);

        expect(fooList.props().foos.size).toBe(3);
    });
});

但是测试失败了,因为它期望长度为3,并且由于某种原因它的实际长度为0 .

我认为它与容器内的提取是异步的事实有关 - 所以测试不是'等待'响应并且渲染在第一次状态改变之前发生并且FooList接收空列表 .

我试图在'it'函数中接收异步回调作为参数并在mount之后调用它,如下所示:

// FooListContainer.test.jsx

describe('rendering', () => {
    it('Should passed the data from the fetch to the FooList', (done) => {
        const response = ['1', '2', '3'];

        manager.bringFooList = jest.fn(() => {
           return new Promise(resolve => {
               return resolve(response);
           });
        })

        const wrapper = mount(<FooListContainer />);
        done();

        const fooList = wrapper.find(FooList);

        expect(fooList.props().foos.size).toBe(3);
    });
});

但上面的例子没有用 . 我非常感谢你能给我的每一个帮助 .