大家。
我在componentDidMount
发生异步通话后测试状态更新时遇到了奇怪的问题。
这是我的组件代码:
'use strict';
import React from 'react';
import UserComponent from './userComponent';
const request = require('request');
class UsersListComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
usersList: []
};
}
componentDidMount() {
request('https://api.github.com/users', (err, res) => {
if (!err && res.statusCode === 200) {
this.setState({
usersList: res.slice(0)
});
}
else {
console.log(err);
}
});
}
render() {
if (!this.state.usersList.length) {
return null;
}
return (
<div className="users-list">
{ this._constructUsersList() }
</div>
);
}
_constructUsersList() {
return this.state.usersList.map((user, index) => {
return (
<UserComponent
key={ index }
name={ user.name }
age={ user.age } />
);
});
}
};
export default UsersListComponent;
现在,我在我的测试文件中做了什么(我有一个由Mocha + Chai + Sinon组成的设置,都在工作):
import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import sinon from 'sinon';
import UsersListComponent from '../src/usersListComponent';
describe('Test suite for UsersListComponent', () => {
it('Correctly updates the state after AJAX call in `componentDidMount` was made', () => {
const server = sinon.fakeServer.create();
server.respondWith('GET', 'https://api.github.com/users', [
200,
{
'Content-Type': 'application/json',
'Content-Length': 2
},
'[{ "name": "Reign", "age": 26 }]'
]);
let wrapper = mount(<UsersListComponent />);
server.respond();
server.restore();
expect(wrapper.update().state().usersList).to.be.instanceof(Array);
console.log(wrapper.update().state().usersList.length);
});
});
即使我在包装器上调用update()
,状态也不会更新。长度仍然是0.我在这里错过了一些东西吗?我是否需要以另一种方式模拟服务器响应?
Thnx的帮助!
答案 0 :(得分:13)
您可以通过传递返回Promise的函数来抽象反应组件的用户列表检索,而不是
componentDidMount() {
request('https://api.github.com/users', (err, res) => {
if (!err && res.statusCode === 200) {
this.setState({
usersList: res.slice(0)
});
}
else {
console.log(err);
}
});
}
将其替换为
componentDidMount() {
var comp = this;
this.props.getUsers()
.then(function(usersList) {
comp.setState({
usersList: usersList
});
})
.catch(function (err) {
console.log(err);
});
}
在你的测试模拟中getUsers
函数:
it('Correctly updates the state after AJAX call in `componentDidMount` was made', (done) => {
let resolveGetUsers;
let getUsers = function() {
return new Promise(function (resolve, reject) {
resolveGetUsers = resolve;
});
}
let wrapper = mount(<UsersListComponent getUsers={getUsers} />);
resolveGetUsers([{ "name": "Reign", "age": 26 }]);
// promise resolve happens in a subsequent event loop turn so move assertions inside setImmediate
setImmediate(() => {
expect(wrapper.update().state().usersList).to.be.instanceof(Array);
...
done();
});
}
请注意,我已经完成了这个并且它适用于我(即使没有wrapper.update()部分),在这里我尝试将它应用于您的代码示例而不运行它。
另请注意,它应该适用于除componentDidMount之外的其他情况 - 例如在单击按钮后触发异步操作。
答案 1 :(得分:1)
我看了https://www.npmjs.com/package/request并发现了&#39;身体&#39;回调中缺少参数。
应该看起来像
...
request('https://api.github.com/users', (err, res, body) => {
if (!err && res.statusCode === 200) {
this.setState({
usersList: body.slice(0)
});
}
...
答案 2 :(得分:0)
请给我我的解决方法:
1-模拟数据服务
您必须模拟数据服务(通常是axios或其他HTTP库之类的东西)。
文件:__mocks__/LogDataService.js
:
let searchData = {}
const LogDataService = {
search: () => new Promise((resolve, reject) =>
process.nextTick(() => resolve(searchData))
),
setSearchData: (data) => searchData = data
}
export default LogDataService
2-测试
文件:__tests__/toto.test.js
:
jest.mock('services/LogDataService')
import LogDataService from 'services/LogDataService';
// Declare a super promise that will synchro all promises
function flushPromises() {
return new Promise(resolve => setImmediate(resolve));
}
it('renders without data', async () => {
// Set dummy data
LogDataService.setSearchData([])
// The component we want to test that use
// LogDataService.search method we just mock up
const component = mount(<JobsExecutionTimeline />);
// wait
await flushPromises();
// re-build the render
component.update()
// Compare to snapshot
expect(toJson(component)).toMatchSnapshot();
});