javascript - 开玩笑等到调用 typemoq 函数
问题描述
所以我有一个模拟(typemoq)http调用,我将它传递给我的反应组件(用酶安装):
const mockhttp: TypeMoq.IMock<IHttpRequest> = TypeMoq.Mock.ofType<IHttpRequest>();
mockhttp
.setup(x => x.get('/get-all-goal-questions'))
.returns(() => {
return Promise.resolve(mockResponse.object.data);
});
const wrapper = mount(<Goals history={Object} http={mockhttp.object} />);
expect(wrapper.find('#foo')).to.have.lengthOf(1);
但是,直到预期之后才会调用模拟“Get”,我怎样才能让期望等到调用模拟进行测试?
// 这里编辑的是被测代码
let httpCall = this.props.pageHoc.httpRequest -- the call im mocking
import React, { Component } from 'react';
import { Row, Col } from 'react-bootstrap';
import { Animated } from "react-animated-css";
import { Answer, IPageHOC } from '../../interfaces/pageObjects';
// Fonts
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCheck } from '@fortawesome/free-solid-svg-icons'
// Cookies
import cookie from 'react-cookies';
// Google analytics
import ReactGA from 'react-ga';
type GoalsComponent = {
answers: Answer[],
showError:boolean,
showAnimation:boolean,
question:string,
questionId:number
};
type Props = {
history:any,
pageHoc?: IPageHOC
}
export default class Goals extends Component<Props, GoalsComponent>
{
constructor(props: any) {
super(props);
this.state = {
answers : [],
showError: false,
showAnimation:false,
question: "",
questionId: 0
}
}
componentDidMount(){
// Hide nav
this.props.pageHoc.hideRightNav();
this.loadQuestions();
}
loadQuestions(){
// Setup auth
let auth = this.props.pageHoc.externalAuth;
auth.setToken(cookie.load('Email'), cookie.load('Password')).then((x) => {
let httpCall = this.props.pageHoc.httpRequest;
// Headers
httpCall.setHeaders({
Organization: cookie.load('Organization')
});
httpCall.get(`/thrive/goal/get-all-goal-questions`)
.then((x) => {
this.setState({
answers:x.data.goalQuestions[0].answers,
question: x.data.goalQuestions[0].question,
questionId: x.data.goalQuestions[0].id
});
})
.catch((x) => {
console.log(x, "error");
});
});
}
render() {
return (
<ul className="list-group list-group-goals">
{this.state.answers.map((x:Answer) =>
<li className={("list-group-item ") + (x.selected ? "selected" : "")} key={x.id} onClick={() => this.toggleGoal(x.id)}>
{x.answer}
<FontAwesomeIcon icon={faCheck} className={("goal-tick ") + (x.selected ? "goal-tick-red" : "")} />
</li>
)}
</ul>
);
}
}
解决方案
嗯,如果你想测试异步请求,你应该遵循这里写的内容: https ://jestjs.io/docs/en/tutorial-async
对于简短版本,您的测试应如下所示:
it('works with async/await', async () => {
expect.assertions(1);
const data = await user.getUserName(4);
expect(data).toEqual('Mark');
});
推荐阅读
- postgresql - PostGreSQL - 控制事务
- html - 如何在 webbrowser 上从此 Html 获取文本?[VB.NET]
- java - 如果第一个完成然后第二个将开始,如何从原始文件夹播放所有 mp3 文件
- github-actions - 使用 GitHub Actions 在 ECS 中注册任务定义失败
- r - gamSpline 插入符号包
- apache-spark - 将数据框注册为临时视图的目的是什么?
- node.js - 有没有办法将用户 ID 传递给架构?
- php - Laravel - AJAX Crud 和 DataTable 显示
- c++ - 区分静态数组、指针和结构的 C++ 模板
- python - 使用 Python 有效计算数组中所有点之间的距离