mardi 9 février 2021

Jest expect statement doesn't wait a promise to be resolved

I am trying to write a test in jest but I need to work with two contexts however I cannot make the expect statement wait for the promise to be resolved before it fires.

The test:

 it("Example test", async() => {
let childComponent = null;
const wrapper = mount (
   <ExampleProviderOne>
      <ExampleConsumerOne>
         {contextOne => {
           context.functionExample = jest.fn();
           context.functionExample.mockImplementationOnce(()=> Promise.resolve(true));
           return(
             <ExampleProviderTwo>
                 <ExampleConsumerTwo>
                    {contextTwo => {return <Component />}}
                 </ExampleConsumerTwo>
             </ExampleProviderTwo>
            )}
      </ExampleConsumerOne>
    </ExampleProviderOne>
});

wrapper.update();
await new Promise(resolve => {
  jest.runAllTimers();
  process.nextTick(resolve);
});

childComponent = wrapper.find(".child-component")
expect(childComponent.length).toBe(1); // exists only after promise is resolved

console.log("End");

The End statement is printed and the expect is executed before the promise is resolved which is not what I want because the child component will exist only when the promise is resolved.

Aucun commentaire:

Enregistrer un commentaire