我编写了一个模拟sumbitChoice()函数的测试,因为这个函数负责API调用。点击按钮'#buttonOption1'即可调用该功能。
目前,测试的断言失败,即预期的模拟函数被调用。'
App.test.js
import React from 'react';
import App from './App';
import { mount, shallow } from 'enzyme';
import { waitForState } from 'enzyme-async-helpers';
describe('App', () => {
it('should call the submitChoice method on click' , () => {
//arrange
const mockSubmitChoice = jest.fn();
const app = mount(<App submitChoice={ mockSubmitChoice } />);
//act
app.find('#buttonOption1').simulate('click');
//assert
expect(mockSubmitChoice).toBeCalled();
})
})
App.js
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = { imageURLs: [] }
}
componentDidMount() {
fetch('/comparison')
.then(res => res.json())
.then(images => this.setState({
imageURLs: [...this.state.imageURLs, images]
}))
// .bind(this);
console.log(this.state)
}
submitChoice(data) {
fetch('/comparison', {
method: 'POST',
body: JSON.stringify([...this.state.imageURLs, data]),
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
render() {
return (
<div className="App">
<img id='firstImage' className='image' src={this.state.imageURLs[0]} />
<img id='secondImage' className='image' src={this.state.imageURLs[1]} />
<button id='buttonOption1' className='button' onClick={this.submitChoice(this.state.imageURLs[0])}>Select Option 1</button>
</div>
);
}
}
export default App;
答案 0 :(得分:0)
尝试在构造函数中绑定this.submitChoice = this.submitChoice.bind(this)
函数。
def findUsedGroups(groupSize,data):
"""Partitions 1-based number lists into groups of groupSize.
Returns amount of groups needed for a given data iterable."""
return len(set ( (x-1)//groupSize for x in data))
alist = [18,5,22,6,38,43]
print(findUsedGroups(7,alist))
答案 1 :(得分:0)
你没有将你的函数绑定到onClick事件,你正在调用它,因为它什么也没有返回,你基本上将undefined绑定到onclick。
这样:
onClick={this.submitChoice(this.state.imageURLs[0])}
与此相同:
onClick-{undefined}
,因为
console.log(this.submitChoice(this.state.imageURLs[0])) // output will be undefined
所以只需改变你的代码:
onClick={this.submitChoice}
并找到另一种传递数据的方法,因为你只是传递静态的数据,所以它不应该是多少问题。
答案 2 :(得分:0)
我最后选择了不同的测试方法。通过了:
it('should call the submitChoice method on click', () => {
//arrange
const spy = jest.spyOn(App.prototype, 'submitChoice');
const app = shallow(<App />);
//act
const button = app.find('#buttonOption1')
button.simulate('click');
//assert
expect(spy).toBeCalled();
})