jupiter / simple-mock

Super simple stubs and spies with 1-step sandbox restore
MIT License
87 stars 12 forks source link

How to mock a function? #32

Closed frankli-dev closed 4 years ago

frankli-dev commented 4 years ago
   const convert = require('pngtojpg');
   ... 
   const result = await convert();

How can I mock convert? simple.mock(convert).resultWith() or simple.mock(convert, 'call').resultWith(), neither is working

Please help me Thanks in advance

frankli-dev commented 4 years ago

Any update?

I also have an issue when mocking fetch function.

const fetch = request('node-fetch');
...
const url = `https://example.com/api`
const response = await fetch(url);

How can I mock this request?

I've tried the following ways but nothing works

simple.mock(fetch).resolveWith("{}");
simple.mock(fetch, 'default').resolveWith("{}");
jupiter commented 4 years ago

Hi,

As node-fetch exports a function as the module, you'd need to change the way you use it. It may not be ideal, but this is how you'd do it:

const fetch = request('node-fetch');
const url = `https://example.com/api`
const response = await fetch.default(url);

And mocking like this:

simple.mock(fetch, 'default').resolveWith("{}");
jupiter commented 4 years ago

For 'png-to-jpg' you might want to look to a module such as https://www.npmjs.com/package/mock-require