Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

330
Views
TypeError: Cannot read property 'then' of undefined Jest and Nest

I'm trying to write a unit test for my NestJS API, but I'm getting this TypeError: Cannot read property 'then' of undefined error when I try to simulate a method in my service class. Could you please explain what is wrong with my code ?

sercice:

async userExist(data: User): Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.usereRepository
        .findOne({
          where: {
            name: data.name,
          },
        })
        .then((res) => {
          if (!res) {
            resolve(false);
          }
          resolve(true);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

async createUser(data: User): Promise<User> {
    return new Promise((resolve, reject) => {
      this.userExist(data).then((exist) => {
        if (exist) {
          return reject('User already exist');
        }
        this.userRepository
          .save(data)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    });
  }

service.test:

it('should create a new user without error', async () => {
      jest
        .spyOn(service, 'userExist')
        .mockImplementation(() => Promise.resolve(false));
      await service.createUser(data);
      expect(userRepository.save).toHaveBeenCalled();
});

I don't know if this is helpful, but I put the beforeEach where I mock my save and findOne database functions.

let service: UserService;
let userRepository: Repository<User>;
beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UserService,
        {
          provide: getRepositoryToken(User),
          useValue: {
            save: jest.fn(),
            findOne: jest.fn(),
          },
        },
      ],
    }).compile();
    service = module.get<UserService>(UserService);
    userRepository = module.get<Repository<User>>(
      getRepositoryToken(User)
    );
  });

error trace

TypeError: Cannot read property 'then' of undefined

      64 |         if (exist) {
      65 |           return reject('User already exist');
    > 66 |         }
         |          ^
      67 |         this.userRepository
      68 |           .save(data)
      69 |           .then((res) => {
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

That is because save() is not an async function, Change it to this:

        {
          provide: getRepositoryToken(User),
          useValue: {
            save: jest.fn().mockResolvedValue('user_object'),
            findOne:jest.fn().mockResolvedValue('user_object'),
          },
        },
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!