Javascript “我该如何嘲笑?”;这";为React模块编写单元测试时?
我正在编写一个React应用程序,其中app.js有很多逻辑,将其余组件连接在一起,并保持一致状态。我已经将App.js中最初的一些代码移到了helpermodule.js中,并绑定了导入的函数,以便它们可以操纵App组件的状态 这是我的设置: App.jsJavascript “我该如何嘲笑?”;这";为React模块编写单元测试时?,javascript,reactjs,unit-testing,mocking,Javascript,Reactjs,Unit Testing,Mocking,我正在编写一个React应用程序,其中app.js有很多逻辑,将其余组件连接在一起,并保持一致状态。我已经将App.js中最初的一些代码移到了helpermodule.js中,并绑定了导入的函数,以便它们可以操纵App组件的状态 这是我的设置: App.js import helperFunction from './helpermodule' class App extends Component { constructor(props) { super(props)
import helperFunction from './helpermodule'
class App extends Component {
constructor(props) {
super(props)
this.state = { foo: 'bar' }
this.helperFunction = helperFunction.bind(this)
}
}
helpermodule.js
function helperFunction() {
this.setState({
bar: 'calculated' + this.state.foo,
})
}
export { helperFunction }
function helperFunction(stateFoo) {
return {bar: 'calculated' + stateFoo};
}
export { helperFunction }
我想为helpermodule中的函数编写一个单元测试。我在酶或Jest文档中找不到相关部分。目标是查看helperFunction对应用程序状态的影响
我尝试过这样的事情
test('helperFunction', () => {
let state = { foo: 'bar' }
let setState = (obj) => { this.state = obj }
return expect(helperFunction().bind(this))
.toBe({
...newShift,
id: 0,
})
}
但这只是返回一个错误<代码>类型错误:无法读取未定义的属性“状态”。也许我的整个方法都是错误的,因此问题可以避免,但我不确定。不要在外部函数中使用this.setState
helpermodule.js
function helperFunction() {
this.setState({
bar: 'calculated' + this.state.foo,
})
}
export { helperFunction }
function helperFunction(stateFoo) {
return {bar: 'calculated' + stateFoo};
}
export { helperFunction }
然后使用结果设置组件中的状态。也不要在构造函数中设置state
import helperFunction from './helpermodule'
class App extends Component {
constructor(props) {
super(props)
this.state = { foo: 'bar', ...helperFunction('bar') }
}
}
这将使测试变得更容易,并且总体上是一个更好的结构。不知道为什么要采用这种方法。这很奇怪,很难遵循和维护,但为了你的论点。问题是您正在将
此
传递到绑定,而此
没有状态
或设置状态
的属性,因此您应该传递模拟的此
这就是它的发展方向
describe('helperFunction', () => {
function helperFunction() {
// @ts-ignore
this.setState({
// @ts-ignore
bar: 'calculated' + this.state.foo,
})
}
it('updates the provided stateHolder', () => {
const stateHolder = {
state: { foo: 'bar' },
// don't use arrow function otherwise it won't react the state via this
setState(obj: any) {
this.state = obj;
},
};
const importedHelperFunction = helperFunction.bind(stateHolder);
importedHelperFunction();
expect(stateHolder.state.foo).toBe('calculatedbar');
});
});
helperFunction
上的设置非常脆弱,您必须始终将其绑定,特别是绑定到react组件。那不好。只需将其添加到你的应用程序中。您还将某些组件状态隐藏在另一个文件中。不要这样做。我同意,但我还没有找到更好的解决办法。我可以将helperFunction放在app.js中,然后在app.js中使用它,但对所有其他helperFunction这样做会很快溢出app.js。在实际的app中,helperFunction会传递给app的子组件,以便它们可以修改app的状态。我很乐意用更好的解决方案来代替它,但我还没有找到。