Search code examples
typescriptunit-testingpromisemeants-mockito

Why do I get an AssertionError: expected MethodToStub on mocking a method returning a promise


On entering a world of MEAN, I am also entering a world of promises.

Now I got this problem:

const promise = new Promise<Boolean>(() => {});
const testObject = mock(DB_DAO_object);
when (testObject.getFlag('value1')).thenReturn(promise.then(()=>{return true;}));
when (testObject.getFlag('value2')).thenReturn(promise.then(()=>{return false;}));

ChaiTest.expect(await testObject.getFlag(value1)).to.be.true;
ChaiTest.expect(await testObject.getFlag(value2)).to.be.false;

And this is the result I hong on for three days....

1) Check if testObject works as expected.
       test promise mocking:

     AssertionError: expected MethodToStub{ …(4) } to be false
      at Context.<anonymous> (test/src/promise.test.ts:121:106)

All code is exemplary... I removed the original values.

Actually I do not understand my failure....


Solution

  • I found a solution.

    const testObject = mock(DB_DAO_object);
    when (testObject.getFlag('value1')).thenResolve(true);
    when (testObject.getFlag('value2')).thenResolve(false);
    const testInstance = instance(testObject);
    
    ChaiTest.expect(await testInstance.getFlag(value1)).to.be.true;
    ChaiTest.expect(await testInstance.getFlag(value2)).to.be.false;