Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest wait until typemoq function called

So I have a mock (typemoq) http call that I'm passing into my react component (mounted with 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);

However, the mock "Get" isn't being called until after the expected, how can I get the expect to wait until the mock is called to test?

// Edit here is the code under test

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>
  
    );
  }
}
like image 333
CerIs Avatar asked Nov 07 '22 13:11

CerIs


1 Answers

hmm if you are trying to test async request you should follow what is written here: https://jestjs.io/docs/en/tutorial-async

for the short version your test should look something like this:

it('works with async/await', async () => {
  expect.assertions(1);
  const data = await user.getUserName(4);
  expect(data).toEqual('Mark');
});
like image 126
Shaked Tayeb Avatar answered Nov 14 '22 21:11

Shaked Tayeb