我是 React 和任何 JavaScript 测试框架的新手。
我有一个简单的组件,可以从 API 检索项目并将其显示在屏幕上。
函数 getItems() 是从 componentWillMount 调用的。
是否可以等到 getItems() 完成后再做出断言?
项目详细信息.js
class ItemDetails extends Component {
constructor(props) {
super(props);
this.state = {
details: ''
}
}
componentWillMount() {
this.getItem();
}
getItem() {
const itemId = this.props.match.params.id;
fetch(`/api/items/${itemId}`)
.then(res => res.json())
.then(details => this.setState({ details }));
}
render() {
const details = this.state.details;
return (
<div>
<h1>{details.title}</h1>
...
</div>
);
}
}
export default ItemDetails;
Run Code Online (Sandbox Code Playgroud)
ItemDetails.test.js
describe('ItemDetails', () => {
it('should render a div with …Run Code Online (Sandbox Code Playgroud) 我为项目实现了基本的缓存功能,并在测试期间遇到了问题。我使用玩笑和redis-mock进行测试,所有测试均通过。问题是当我导入一个导入redis文件的文件时。测试文件不会退出。
例:
index.test.js
import redis from 'redis'
import redis_mock from 'redis-mock'
jest.spyOn(redis, 'createClient').mockImplementation(red_mock.createClient)
import fileUsingRedis from './index'
describe('index', () => {
it('should pass', () => expect(true).toBeTruthy())
}
Run Code Online (Sandbox Code Playgroud)
index.js
import {set} from './redis'
export default function ...
Run Code Online (Sandbox Code Playgroud)
redis.js
import redis from 'redis'
const client = redis.createClient()
export function set(key, value) {...}
Run Code Online (Sandbox Code Playgroud)
'1通过'...'跑所有匹配的测试套件...'
但是随后它一直在等待,因为reis.createClient()是异步的或其他原因。看到导入时发生的情况,我不能仅仅解决它。每次测试后是否都必须关闭redis-instance连接?
解决方案/最佳做法是什么?