1

I have two methods: second one is called by the first and I have to write test for the first one.

function func1(props, num) {
    num.value +=1;
    func2(props, num);
}
    
function func2(props, num) {
    props.actions.getItDone().then((res) => {
    num.value+=res.payload;
    console.log(num);//i see 6 here but not in the test result.
    });
}

Unit test file:

const props = {
    actions: {
        getItDone: () => {
            return Promise.resolve({payload: 5 })
        }
    }
}
it('should verify something', () => {
    const num = {value: 0};
    func1(props, num);
    expect(num.value).toBe(6); // it fails num.value coming here is 1.
});

it seems to me it's not waiting for the other method to complete. how can i make this return the correct value?

2 Answers2

0

You do not seem to be injecting the props you are defining in your unit test file into func2. How is the func2 supposed to know that it is supposed to use the props in that other file?

You should add props as a parameter or override them in the place where func2 gets the variable from.

timmeinerzhagen
  • 772
  • 7
  • 10
  • thanks, i tried adding Props, and i also added logger, I can see value getting 6, but in the test result, it is still coming as 1. – Abhicruiser Aug 09 '21 at 18:55
0

You are not waiting for the Promise to resolve. If you care about knowing when the promise in func2 is resolved, you'll have to modify your code to return the promises and then wait on them, before asserting. Something like this will solve the problem

function func1(props, num) {
  num.value += 1;
  // notice the return
  return func2(props, num);
}

function func2(props, num) {
  // notice the return
  return props.actions.getItDone().then((res) => {
    num.value += res.payload;
  });
}

it("should verify something", async () => {
  const num = { value: 0 };

  await func1(props, num);
  expect(num.value).toBe(6);
});

Also note the usage of async-await in the test. I chose to put it because you've tagged the question with async-await. So, thought it be a good idea to show you how you can "wait" for the function to complete.

maazadeeb
  • 5,922
  • 2
  • 27
  • 40