簡體   English   中英

Mocking Date.Now jest toHaveBeenCalledWith in nestJs

[英]Mocking Date.Now jest toHaveBeenCalledWith in nestJs

我想弄清楚如何在我的 nestjs 應用程序中用 jest 模擬對 Date.now 的調用。

我有一個軟刪除資源的存儲庫方法

async destroy(uuid: string): Promise<boolean> {
  await this.userRepository.update({ userUUID: uuid }, { deletedDate: Date.now() });
  return true;
}

要軟刪除,我們只需添加請求刪除的時間戳

經過在這里和其他網站上的一些討論,我想出了這個測試。

  describe('destroy', () => {
    it('should delete a user schemas in the user data store', async () => {
      const getNow = () => Date.now();
      jest
        .spyOn(global.Date, 'now')
        .mockImplementationOnce(() =>
          Date.now().valueOf()
        );
      const targetResource = 'some-uuid';
      const result = await service.destroy(targetResource);
      expect(result).toBeTruthy();
      expect(userRepositoryMock.update).toHaveBeenCalledWith({ userUUID: targetResource }, { deletedDate: getNow() });
    });
  });

我假設 .spyOn(global.Date) 模擬了整個全局 dat 函數,但我的存儲庫中的 Date.now() 仍然返回實際日期而不是模擬。

我的問題是,有沒有辦法提供從測試中調用的 Date.now 的模擬返回值,還是我應該直接將 DateProvider 注入存儲庫類,然后我可以從我的測試中模擬?

jest.spyOn(Date, 'now')應該可以工作。

例如

userService.ts :

import UserRepository from './userRepository';

class UserService {
  private userRepository: UserRepository;
  constructor(userRepository: UserRepository) {
    this.userRepository = userRepository;
  }
  public async destroy(uuid: string): Promise<boolean> {
    await this.userRepository.update({ userUUID: uuid }, { deletedDate: Date.now() });
    return true;
  }
}

export default UserService;

userRepository.ts

class UserRepository {
  public async update(where, updater) {
    return 'real update';
  }
}

export default UserRepository;

userService.test.ts

import UserService from './userService';

describe('60204284', () => {
  describe('#UserService', () => {
    describe('#destroy', () => {
      it('should soft delete user', async () => {
        const mUserRepository = { update: jest.fn() };
        const userService = new UserService(mUserRepository);
        jest.spyOn(Date, 'now').mockReturnValueOnce(1000);
        const actual = await userService.destroy('uuid-xxx');
        expect(actual).toBeTruthy();
        expect(mUserRepository.update).toBeCalledWith({ userUUID: 'uuid-xxx' }, { deletedDate: 1000 });
      });
    });
  });
});

100% 覆蓋率的單元測試結果:

 PASS  stackoverflow/60204284/userService.test.ts
  60204284
    #UserService
      #destroy
        ✓ should soft delete user (9ms)

----------------|---------|----------|---------|---------|-------------------
File            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------------|---------|----------|---------|---------|-------------------
All files       |     100 |      100 |     100 |     100 |                   
 userService.ts |     100 |      100 |     100 |     100 |                   
----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.572s, estimated 11s

源代碼: https : //github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60204284

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM