gpt4 book ai didi

javascript - 开 Jest 等到 typemoq 函数被调用

转载 作者:搜寻专家 更新时间:2023-11-01 04:39:14 26 4
gpt4 key购买 nike

所以我有一个模拟(typemoq)http 调用,我将其传递到我的 react 组件(安装有 enzyme ):

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');
});

关于javascript - 开 Jest 等到 typemoq 函数被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58116146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com