简体   繁体   English

开玩笑:模拟嵌套的 function 多次返回键/值对

[英]Jest: Mock a nested function which returns key/value pairs multiple times

I am writing a test for an API which calls a nested api multiple times to get a key value pair.我正在为 API 编写测试,它多次调用嵌套的 api 以获得键值对。 The value will always be a boolean and I am trying to mock this service aka KeyValueService in the code below.该值将始终为boolean ,我试图在下面的代码中模拟此服务,即KeyValueService These and other more booleans are used in the PhotoService and I would like to mock these values so I can change the test to match these values. PhotoService中使用了这些和其他更多布尔值,我想模拟这些值,以便我可以更改测试以匹配这些值。

I have mocked the booleans and also tried setting mockResolveValuetwice to true twice thinking that it may apply true for both variables valueA and valueB , but it did not work.我嘲笑了布尔值,还尝试将mockResolveValuetwice设置为true两次,认为它可能对变量valueAvalueBtrue ,但它没有用。 I will be using this nested service multiple times and not just twice.我将多次使用此嵌套服务,而不仅仅是两次。 So far none of the solutions worked.到目前为止,没有任何解决方案奏效。 How can I get a desired value for each key value pair?如何为每个键值对获得所需的值? TIA! TIA!

jest.mock('../../service/keyValue.service', () => ({
  valueA: false,
  valueB: false
}));

describe('PhotosService', () => {
  let service: PhotosService;
  let keyValueService: KeyValueService;
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [PhotosService],
    }).compile();
    
    service = module.get<PhotosService>(PhotosService);
    keyValueService.get.mockResolveValue(() => true);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
    valueA.mockResolveValue(() => true);
  });
});

But the values doesnt change.但价值观不会改变。 I also tried the following,我还尝试了以下,

  it('should be defined', () => {
    keyValueService.get.mockResolveValue(true);
    keyValueService.get.mockResolveValue(true);
    expect(service).toBeDefined();
    valueA.mockResolveValue(() => true);
  });

Alright one thing that worked for me was to set keyValueService.get again in my test or it block to jest.fn() again which worked for me to resolve this issue.好吧,对我有用的一件事是在我的test中再次设置keyValueService.get或者it再次阻止jest.fn() ,这对我来说解决了这个问题。

keyValueService.get = jest.fn()...;

Upto to use what you want.最多使用你想要的。 Either mockImplementation if need be or mockReturnValue etc. My guess is that it just reassigns the get function to a new mock value for that particular it/test block. mockImplementation如果需要)或mockReturnValue等。我的猜测是它只是将get function 重新分配给特定it/test块的新模拟值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM