代码之家  ›  专栏  ›  技术社区  ›  nerrood

为什么在笑话测试中不调用save

  •  0
  • nerrood  · 技术社区  · 11 月前

    我在检查是否调用了我模拟的“保存”方法时遇到了问题。每次运行测试时,我都会得到调用次数为===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)
        ```
    
    1 回复  |  直到 11 月前
        1
  •  1
  •   Micael Levi    11 月前

    可能是因为一个失踪 await expect..resolves..

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