Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
How to test promise with try and catch a function like this example

I cannot test the reject for some reason. Here is the function and I want to test it 100%. now it is like 92% and complain about reject(e) is not tested..

  public resolve(): Promise<{ [key: string]: boolean }> {
    return new Promise<{ [key: string]: boolean }>(async (resolve, reject) => {
      try {
        for await (const setting of settings) {
          // ObjectStore that acts like hashMap
          this.store.set(setting.key, setting.value);
        }
        resolve();
      }
      catch (e) {
        reject(e);
      }
    });
  }

Updates:

I have to make another Mock to make the catch statement happening first. And TestBed.overrideProvider is not really working for me, so that I have to

  it('should return a rejected promise', async() => {
    TestBed.resetTestingModule();
    TestBed.configureTestingModule({ 
//inserting the new mock provider to trigger the catch 
... 
});

and then use the answer below (Thank you @Apoorva Chikara) and works for me

If there is easier way to accomplish this, please let me know

Here is my updated code for testing.

  it('should return a rejected promise', async() => {
    TestBed.resetTestingModule();
    TestBed.configureTestingModule({
      providers: [
        {
          provide: ObjectStore,
          useValue: new ObjectStore('test'),
        },
        {
          // Making this client invalid to trigger catch and throw error
          // I think writing a mock class to throw error also can be done
          // this is the "settings" from azure listConfigurationSettings 
          provide: AppConfigurationClient,
          useValue: {},
        }
      ]
    });
    service = TestBed.inject(FeatureFlagResolver);
    store = TestBed.inject(ObjectStore);
    const rejection = async () => {
      await service.resolve().catch();
    }
    await expect(rejection()).rejects.toThrow();
  });

The "settings" is listConfigurationSettings from MS azure. we used to read from azure for configuration settings. For example, we want to enable certain thing(s) in the Angular site, we can go to azure portal to change app-setting ("chatbot", 'on'), so that the chatbot will be on the page.. Just app settings that people to toggle on, off for now.

Sorry I should have included more information in the first place.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Never pass an async function as the executor to new Promise! Your function should be simplified to

public async resolve(): Promise<{ [key: string]: boolean }> {
//     ^^^^^
  for await (const setting of settings) {
    // ObjectStore that acts like hashMap
    this.store.set(setting.key, setting.value);
  }
}

and then you won't need a separate test for the code path that doesn't even exist.

Furthermore, you probably don't want to use for await, unless settings is an asynchronous generator. Given the updated details, it actually is a PagedAsyncIterableIterator. I would however recommend not to store that in a global variable, but do the iteration in the same function where the .listConfigurationSettings() call is done.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can catch the error and test it. It is similar to testing the resolving.

  describe('Test Case', () => {
    describe('Testing Sample 1', () => {
      it('should return a rejected promise', () => {
        service.resolve()
          .catch((error) => {
            expect(error).toEqual('the error string');
          });
      });
    });
  });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda