使用 sinon 为 POST 请求模拟提取 API,为 react.js 应用程序开玩笑
Mocking fetch API for POST request using sinon, jest for react.js application
我想测试 post 获取 API 的请求,该请求是在单击按钮时启动的。为了模拟 fetch api 请求,我使用了 sinon
库。假服务器是活的,但不提供响应 JSON 对象。这里的apiUrl
是http://localhost:5000/api/users
,userData是{ sid: 1, sname: 'test'}
.
这是 App.test.js 文件
describe('test api',()=>{
let server;
beforeEach(() => {
server = fakeServer.create();
server.respondWith('POST',
apiUrl,
[
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(userData)
]
);
});
describe('app component', () => {
const app = mount(<App />);
beforeEach(() => {
app.find('Button').simulate('click');
});
it('get data from server', done => {
server.respond();
setTimeout(done);
});
it('updates state', () => {
expect(app.state().user).toEqual('user1') // fails
})
});
});
已编辑:
应用组件
class App extends Component {
constructor() {
super();
this.state = {
serialNum: ''
user: ''
}
}
submitUrl = async () => {
const postData = { sid: this.state.serialNum, sname: 'something'};
try {
let response = await fetch('http://localhost:5000/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData)
});
response = await response.json();
if (result) {
this.setState({ user: response.username});
}
} catch (err) {
console.log('Error:', err);
}
}
render() {
return (
<div className="container">
<div className="col">
<Form>
<FormGroup>
<div className="row input-container">
<FormControl placeholder="Enter value"
onChange={(e) => this.setState({
serialNum: e.target.value
})} />
</div>
<div className="row">
<Button variant="primary"
className="submit-btn"
onClick={this.submitUrl}>Submit</Button>
</div>
</FormGroup>
</Form>
</div>
</div>
);
}
}
export default App;
我在这里错过了什么?服务器请求成功或失败如何调试?我在模拟按钮点击后调用 server.respond()
并要求 Jest 等待服务器通过传递 done
参数完成请求。
为什么不直接模拟获取函数本身,而不是服务器。所以:
describe('app component', () => {
const app = mount(<App />);
beforeEach(() => {
global.fetch = jest.fn().mockImplementation(() => {
return Promise.resolve(new Response(JSON.stringify({ sid: 1, sname: 'test' })));
});
app.find('Button').simulate('click');
});
it('updates state', () => {
expect(app.state().user).toEqual('user1') // fails
})
});
请记住,您是在此处测试数据获取后的状态更改,只需模拟获取函数就足以充分测试您的逻辑。
我想测试 post 获取 API 的请求,该请求是在单击按钮时启动的。为了模拟 fetch api 请求,我使用了 sinon
库。假服务器是活的,但不提供响应 JSON 对象。这里的apiUrl
是http://localhost:5000/api/users
,userData是{ sid: 1, sname: 'test'}
.
这是 App.test.js 文件
describe('test api',()=>{
let server;
beforeEach(() => {
server = fakeServer.create();
server.respondWith('POST',
apiUrl,
[
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(userData)
]
);
});
describe('app component', () => {
const app = mount(<App />);
beforeEach(() => {
app.find('Button').simulate('click');
});
it('get data from server', done => {
server.respond();
setTimeout(done);
});
it('updates state', () => {
expect(app.state().user).toEqual('user1') // fails
})
});
});
已编辑:
应用组件
class App extends Component {
constructor() {
super();
this.state = {
serialNum: ''
user: ''
}
}
submitUrl = async () => {
const postData = { sid: this.state.serialNum, sname: 'something'};
try {
let response = await fetch('http://localhost:5000/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData)
});
response = await response.json();
if (result) {
this.setState({ user: response.username});
}
} catch (err) {
console.log('Error:', err);
}
}
render() {
return (
<div className="container">
<div className="col">
<Form>
<FormGroup>
<div className="row input-container">
<FormControl placeholder="Enter value"
onChange={(e) => this.setState({
serialNum: e.target.value
})} />
</div>
<div className="row">
<Button variant="primary"
className="submit-btn"
onClick={this.submitUrl}>Submit</Button>
</div>
</FormGroup>
</Form>
</div>
</div>
);
}
}
export default App;
我在这里错过了什么?服务器请求成功或失败如何调试?我在模拟按钮点击后调用 server.respond()
并要求 Jest 等待服务器通过传递 done
参数完成请求。
为什么不直接模拟获取函数本身,而不是服务器。所以:
describe('app component', () => {
const app = mount(<App />);
beforeEach(() => {
global.fetch = jest.fn().mockImplementation(() => {
return Promise.resolve(new Response(JSON.stringify({ sid: 1, sname: 'test' })));
});
app.find('Button').simulate('click');
});
it('updates state', () => {
expect(app.state().user).toEqual('user1') // fails
})
});
请记住,您是在此处测试数据获取后的状态更改,只需模拟获取函数就足以充分测试您的逻辑。