TypeError: test is not a function [ Jest ] [express ]

2023. 7. 12. 18:02에러대응

개요

 

jest 를 이용해 service 단에서 단위테스트를 연습하다 겪은 에러이다.

 


에러 코드

 FAIL  __tests__/unit/posts.service.unit.spec.js
  ● Test suite failed to run

    TypeError: test is not a function

      18 |   });
      19 |
    > 20 |   test("Posts Service findAllPosts Method", async () => {
         |   ^
      21 |     const findAllPostReturnValue = [
      22 |       {
      23 |         postId: 1,

      at test (__tests__/unit/posts.service.unit.spec.js:20:3)
      at Object.describe (__tests__/unit/posts.service.unit.spec.js:15:1)

실제 코드

 

// posts.service.unit.spec.js

//...

describe("Layerd Architecture Pattern Posts Service Unit Test", () => {
  beforeEach(() => {
    jest.resetAllMocks();
  });

  test("Posts Service findAllPosts Method", async () => {
    const findAllPostReturnValue = [
      {
        postId: 1,
        userId: 1,
        nickname: "test nickname 1",
        title: "test title 1",
        createdAt: new Date("11 October 2022 00:00"),
        updatedAt: new Date("11 October 2022 00:00"),
      },
      {
        postId: 2,
        userId: 2,
        nickname: "test nickname 2",
        title: "test title 2",
        createdAt: new Date("12 October 2022 00:00"),
        updatedAt: new Date("12 October 2022 00:00"),
      },
    ];

// ...
  });
});
// posts.service.js

const PostsRepository = require("../repositories/posts.repository");
const { Posts, Users, Likes } = require("../models");

class PostService {
  postsRepository = new PostsRepository(Posts, Users, Likes);

// ...

  findAllPosts = async () => {
    const posts = await this.postsRepository.findAllPosts();

    const postsData = posts.map((post) => {
      return {
        postId: post.postId,
        userId: post.userId,
        nickname: post.dataValues.nickname,
        title: post.title,
        createdAt: post.createdAt,
        updatedAt: post.updatedAt,
        likes: post.dataValues.likes,
      };
    });

    return postsData;
  };

// ...
}

module.exports = PostService;

해결 과정

 

에러는 자주 보던에러다. test 를 불러오지 못하는 듯 했다.

구글에서 검색을 해보고 test 를 it 으로 바꿔보았으나 다른 에러가 발생했다.

 

test 의 첫번째 인자인 문자열이 겹치나 해서 바꿔도 보았다.

 

또 참고하던 강의를 보고 따라서도 해봤으나 같은 오류가 발생하였습니다.

 

다음에 시도한 방법이 도움이 되었습니다.

 

npm install @jest/globals

 

// posts.service.unit.spec.js

const { jest, describe, test, beforeEach, expect } = require("@jest/globals")

// ...

 

이렇게 변경하고 실행해 보았더니 또 다른 에러가 발생하였다.

 

    SyntaxError: Identifier 'jest' has already been declared

 

jest 가 이미 선언되어있다고 한다.

그래서 다음과 같이 수정했다.

 


해결

// posts.service.unit.spec.js

const { describe, test, beforeEach, expect } = require("@jest/globals");

// ...

 

이렇게 바꿔주니 잘 작동했다.

왜이런문제가 생겼는지 조금 알아보니 

 

.spec.js 파일을 생성하게 되면 기본적으로 jest 의 의존성이 해당 파일에서 import 된다고 한다.

 

그래서 이번 이슈는 jest 가 사용하는 특정 메서드가 postservice.spec.js 파일에서 Import 되지 않아 발생한 에러인 것이다.