为什么在 jest test 中没有调用 save

问题描述 投票:0回答:1

我在检查我的模拟“保存”方法是否已被调用时遇到问题。每次当我运行测试时,我都会得到调用次数 === 0 的信息,但在生产中一切正常,新数据被保存,并且 orm save 方法被正确调用。

这是我的示例测试

 describe('updateEmail', () => {
    it('should update user email', async () => {
      const user: User = {
        id: 'abc',
        email: '[email protected]',
        password: 'password',
      };

      const updatedUser: User = Object.assign({}, user);
      updatedUser.email = '[email protected]';

      const findOneSpy = jest
        .spyOn(repository, 'findOne')
        .mockResolvedValue(user);

      const saveSpy = jest
        .spyOn(repository, 'save')
        .mockResolvedValue(updatedUser);

      expect(
        service.updateEmail({
          oldEmail: user.email,
          newEmail: updatedUser.email,
        }),
      ).resolves.toEqual(updatedUser);

      expect(findOneSpy).toHaveBeenCalledWith({ where: { email: user.email } });

      expect(saveSpy).toHaveBeenCalledWith(updatedUser);
    });
  });

还有简单的逻辑

async updateEmail({ oldEmail, newEmail }: UpdateEmailDto) {
    const user = await this.findByEmail(oldEmail);

    if (!user) throw new NotFoundException();

    user.email = newEmail;

    return this.usersRepository.save(user);
  }

这也是我从 cli 得到的错误

 expect(jest.fn()).toHaveBeenCalledWith(...expected)

    Expected: {"email": "[email protected]", "id": "abc", "password": "password"}

    Number of calls: 0

      133 |       expect(findOneSpy).toHaveBeenCalledWith({ where: { email: user.email } });
      134 |
    > 135 |       expect(saveSpy).toHaveBeenCalledWith(updatedUser);
          |                       ^
      136 |     });
      137 |   });
      138 | });

      at Object.<anonymous> (users/users.service.spec.ts:135:23)
    ```
testing jestjs nestjs
1个回答
0
投票

可能是因为

await
 处缺少 
expect..resolves..

查看笑话文档:https://jestjs.io/docs/asynchronous

© www.soinside.com 2019 - 2024. All rights reserved.