Использование Jest ожидало, что фиктивная функция была вызвана один раз, но она вызывалась ноль раз

#mocking #jestjs #react-testing-library

#издевательство #jestjs #react-testing-library

Вопрос:

Я новичок в среде тестирования Jest, и поэтому я не хочу слишком издеваться над функцией, которая возвращает обещание протестировать мою кнопку события нажатия. Я получаю сообщение об ошибке, в котором говорится, что мой метод не был вызван, но я определил его ниже как jest.fn () и ожидаю, что он будет вызван один раз. Любая помощь в решении этого или некоторая ясность в отношении того, почему мой код неправильный.

 const props = {
        activitiesStore: {
          isFirst:false,
          isLast:false,
          isLaunching:false,
          isLoaded:false,
          currentActivityIndex:115,
          markLessonFinished:() => {

          },
          setContent:{
            description: "In the CompTIA A  training course, you will learn the fundamentals of computer technology, repair, basic networking, installation and configuration of PCs, laptops and related hardware, as well as configurations for the mobile OS's Android and Apple iOS."
          },
          activityRespone:{
            description:"**TCP/IP Configuration Default Gateway** For this lesson, we take a closer more intimate look at the Default Gateway and how that process works. This is where the computer goes to get out of a network…",
            lesson_id:116,
            no_iframe:false,
            slug:"tcpip-configurations-default-gateway",
            type:"Video Activity",
            url:"https://player.vimeo.com/video/113658225"
          },
          activities:[{
            completed:true,
            content_description_id:2,
            course_id:178,
            moduleId:4649,
            thumbnail:"https://dev.cybrary.it/wp-content/themes/cybrary/teamsv2/img/certification_labs.png",
            title:"About Anthony Harris"
          }],
          advertisements:[{
            href:"https://www.cybrary.it",
            image:"https://www.cybrary.it/wp-content/uploads/2018/12/VideoPage-XMAS40.png",
            objectID:"787592",
            section:"immersive",
            weight:0
          }],
          currentActivity:{
            completed:true,
            content_description_id:117,
            course_id:178,
            moduleId:4665,
            thumbnail:"https://dev.cybrary.it/wp-content/themes/cybrary/teamsv2/img/certification_labs.png",
            title:"TCP/IP Configurations Default Gateway",
            currentActivityIndex:115
          },
          enrollment:{
            estimatedCompletionDate: "Aug 21, 2019",
            estimatedTimeRemaining: "31 hours 38 minutes",
            id: 37,
            isLate: true,
            overallProgress: 33,
            programDeadline: "May 17, 2018",
            status: "Started",
            thumbnail: "/images/assignment_16.jpg",
            title: "testing admin curry",
            totalCompletedCurriculumItems: 0,
            totalCurriculumItems: 1,
            totalStartedCurriculumItems: 1,
            type: "Assignment",
            settings:[{

            }],
            progressData:[{
              progress: 100,
              title: "Session 1",
              duration:null,
              checkpointDate: "Sep 30, 2018",
              content:[{
                content:{
                  duration: " 1 minute",
                  status: "Completed",
                  title: "Instructor Background - About Anthony Harris"
                },
                icon:"play"
              }],
              headerColumns:[{
                title: "Progress",
                value: "100%"
              }],
              headerRow:[{
                content:"LAUNCH"
              }]
            }],
            moduleActivities:[[{
              duration: 110,
              id: 2,
              progress: 100,
              title: "About Anthony Harris",
              _course_id: 178,
              _formatted_title: "Instructor Background - About Anthony Harris",
              _is_completed: true
            }]],
            enrollmentTableData:[{
              duration: "44 hours 16 minutes",
              estimatedTimeRemaining: "31 hours 38 minutes",
              progress: 33,
              remainingDuration: "31 hours 38 minutes",
              status: "In Progress",
              thumbnail: "https://dev.cybrary.it/wp-content/themes/cybrary/teamsv2/img/certification_labs.png",
              title: "Comptia A  (Archive)",
              type: "Course",
              curriculumItem:{
                legacy_id: 167,
                video_intro_url: "https://player.vimeo.com/video/208046939",
                id:178,
                content_description_id:4648,
                content_description:{
                  courseId: 178,
                  duration_seconds: 154800,
                  id: 4648,
                  is_hidden: 1,
                  content_type:{
                    human_readable_name: "Course",
                    id: 1,
                    name: "course",
                    thumbnail_url: "https://dev.cybrary.it/wp-content/themes/cybrary/teamsv2/img/certification_labs.png"
                  }
                }
              },
              contentDescription:{
                courseId: 178,
                duration_seconds: 154800,
                id: 4648,
                is_hidden: 1,
                content_type:{
                  human_readable_name: "Course",
                  id: 1,
                  name: "course",
                  thumbnail_url: "https://dev.cybrary.it/wp-content/themes/cybrary/teamsv2/img/certification_labs.png"
                }
              }
            }],
            curriculumItems:[{
              duration: "44 hours 16 minutes",
              estimatedTimeRemaining: "31 hours 38 minutes",
              progress: 33,
              remainingDuration: "31 hours 38 minutes",
              status: "In Progress",
              thumbnail: "https://dev.cybrary.it/wp-content/themes/cybrary/teamsv2/img/certification_labs.png",
              title: "Comptia A  (Archive)",
              type: "Course",
              curriculumItem:{
                legacy_id: 167,
                video_intro_url: "https://player.vimeo.com/video/208046939",
                id:178,
                content_description_id:4648,
                content_description:{
                  courseId: 178,
                  duration_seconds: 154800,
                  id: 4648,
                  is_hidden: 1,
                  content_type:{
                    human_readable_name: "Course",
                    id: 1,
                    name: "course",
                    thumbnail_url: "https://dev.cybrary.it/wp-content/themes/cybrary/teamsv2/img/certification_labs.png"
                  }
                }
              },
              contentDescription:{
                courseId: 178,
                duration_seconds: 154800,
                id: 4648,
                is_hidden: 1,
                content_type:{
                  human_readable_name: "Course",
                  id: 1,
                  name: "course",
                  thumbnail_url: "https://dev.cybrary.it/wp-content/themes/cybrary/teamsv2/img/certification_labs.png"
                }
              }
            }],
            loading:{

            }
          }
        }
  
 markLessonFinished() {
    const currentActivity = this.currentActivity;
    return new Promise(resolve => {
      if (
        this.activityResponse amp;amp;
        this.activityResponse.lesson_id amp;amp;
        currentActivity.course_id
      ) {
        Agents.catalog
          .finishLesson(
            this.activityResponse.lesson_id,
            currentActivity.course_id
          )
          .then(() => {
            resolve(true);
          });
      }
      resolve(false);
    });
  }
  
 it("should click next button after lesson finished", async () => {

        const { getByText } = render(<ImmersivePage {...props}/>)

        // checks if 'Next' button is rendered
        expect(getByText("Next")).toBeTruthy()

        const markLessonFinished = jest.fn()

        await waitForElement(() => {
            expect(markLessonFinished).toHaveBeenCalledTimes(1)
        }).then(() => {
            fireEvent.click(getByText("Next"))
        })
    })
  

Ответ №1:

Вы должны передать свой издевательский метод компоненту, который вы визуализируете:

 const markLessonFinished = jest.fn().mockResolvedValue(true)
const { getByText } = render(<ImmersivePage {...props} markLessonFinished={markLessonFinished} />)
  

На данный момент я не уверен, как работает ваш компонент, но я предполагаю, что сначала вы нажимаете кнопку, а затем урок помечается как законченный. В этом случае вы бы сделали:

 fireEvent.click(getByLabelText('Next'))
await wait(()=> expect(markLessonFinished).toHaveBeenCalledTimes(1))
  

Комментарии:

1. Что, если я хочу издеваться над этой функцией как над обещанием, которое разрешает true .

2. ожидание ожидания (()=> ожидать (markLessonFinished). toHaveBeenCalledTimes(1)) была единственной строкой, которая мне была нужна из этого