Lusito / mockzilla

A mocking toolkit leveraging the power of TypeScript to enhance your jest experience.
https://lusito.github.io/mockzilla/
zlib License
14 stars 2 forks source link

How to test Mockzilla error #8

Closed Janaka-Steph closed 3 years ago

Janaka-Steph commented 3 years ago

Hello,

Writing Jest tests I would like to verify that mockBrowser.storage.local.get.expect('wallets') has not been called. It should throw a Mockzilla error Missing 1 calls to browser.storage.local.get() as seen here https://github.com/Lusito/mockzilla/blob/master/src/node.ts#L245. However it doesn't throw in the expect, so I can't test it. Any idea how to solve this? Thanks!

Lusito commented 3 years ago

Hi,

With mockzilla, you first define the expectations and when an unexpected call happens, the tests will fail. So if you want to ensure, that a certain function has not been called, just remove the expect statement.

So, in other words: The statement mockBrowser.storage.local.get.expect('wallets') only configures the mock to expect that call to be made. The actual error will be thrown when the code executes.

examples:

mockBrowser.storage.local.get.expect('wallets')
browser.storage.local.get('wallets') // ok
mockBrowser.storage.local.get.expect('wallets')
browser.storage.local.get('money') // throws
// not called: mockBrowser.storage.local.get.expect('wallets')
browser.storage.local.get('wallets') // throws
Janaka-Steph commented 3 years ago

The thing is that in my src I call browser.storage.local.get('wallets') conditionally. I wanted to test that the 'else' path is taken, not calling storage. From what I understand this is not possible.

Lusito commented 3 years ago

It really depends on your test. Without knowing your test code, I can only assume one of these two solutions:

Write one test block for condition=true and one for condition=false

it("does stuff with condition=true", () => {
    mockBrowser.storage.local.get.expect('wallets');
    runCode(true);
});
it("does stuff with condition=false" () => {
    runCode(false);
});

Write the test block conditionally as well

if you have one block to test both scenarios (for example with it.each()()), you put the expect() block in a condition too:

it.each([[true],[false]])("does stuff with condition=%b", (condition) => {
    if (condition) mockBrowser.storage.local.get.expect('wallets');
    runCode(condition);
});
Janaka-Steph commented 3 years ago

Ok I will see that. Thank you very much for your help.