如何正确测试React组件中的方法,例如componentDidMount。我想测试组件内部的setTimeOut函数。我应该使用stub吗?例如下面的代码:
componentDidMount() {
setTimeout(() => this.setState({ isOpen: true }), 1);
}
我该如何测试setTimeout是否被调用?
我尝试了以下方法,但没有成功。我错过了什么吗?
my imports:
import test from 'ava';
import React from 'react';
import { ad } from 'components/Ad/Ad';
import { shallow, mount } from 'enzyme';
import { stub } from 'sinon';
import { expect } from 'chai';
import sinon from 'sinon';
let info;
test.beforeEach(() => {
info = shallow(<ad {...props} />)
});
test('is active: true after mounting', done => {
info.instance().componentDidMount()
setTimeout(() => {
info.state('active').should.be.true <--line:42
done()
}, 0)
})
我遇到了以下错误: TypeError: 无法读取未定义的属性'be' null._onTimeout (test/Components/Ad.unit.js:42:5)
setTimeOut
是你自己的函数还是你指的是setTimeout
?无论哪种情况,你究竟想要测试什么? - Tom Fenech