Использование Jest ожидало, что фиктивная функция была вызвана один раз, но она была вызвана ноль раз - PullRequest
0 голосов
/ 28 марта 2019

Я новичок в инфраструктуре тестирования Jest, и поэтому я не буду слишком издеваться над функцией, которая возвращает Promise для проверки моей кнопки события click. Я получаю сообщение об ошибке, в котором говорится, что мой метод не был вызван, но я определил его ниже как 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 &&
        this.activityResponse.lesson_id &&
        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 Ответ

0 голосов
/ 28 марта 2019

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

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

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

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