Open yuv-c opened 2 years ago
I've re-written my use of rewiremock, and am able to get it to mock properly:
serverFile = rewiremock.proxy(() => require('../server/src/server'), {
'@data/utils/server-auth-client': {
authentication: authenticationMock,
authorization: authorizationMock
},
'@data/utils/queries-loader': {
loadFromFS: mockLoadFromFS
}
});
rewiremock.overrideEntryPoint(module);
Notice that loadFromFS isn't directly required by server.js
, so it was unclear i should be mocking it from there.
I do have another question - Is it possible to proxy(() => '../server/src/server'), {mockA}
inside before
function, and then mock other requires used by '../server/src/server' later during the test?
Hey, sorry for quite a late answer, but it's better late that never?
History note - rewiremock supports different "models" of work in order to help migration from other libraries existing before it. rewiremock.proxy
is mimicking proxyquire
interface.
In short proxy(file, overrides)
returns you a file
with overrides 🤷♂️ overrides. Depending on different flags it can be direct children only, or any transitive dependency required by this file anywhere.
If you want to mocks something else in the same test you need to do const newServer = .proxy
stuff again.
At the same time you can change rules a little bit and mock @data/utils/queries-loader
instead of '../server/src/server'
rewiremock('@data/utils/queries-loader').with({loadFromFS: mockLoadFromFS});
const serverFile = require('../server/src/server');
In this you can do the following trick
const loaderMock = rewiremock('@data/utils/queries-loader')
.callThrough() // pass to real file
.dynamic() // allow changes in the future
const serverFile = require('../server/src/server');
// update mocking in the future
loaderMock.with({loadFromFS: mockLoadFromFS});
Keep in mind dynamic
wraps module export in Proxy to be able to update it at runtime and some operations (assigning to a constant) can bypass it. So I cannot guarantee that it gonna work for every case.
I am trying to test an express API. Upon calling one of the endpoints, the API calls the function
loadFromFS
. I'd like to mock its return value. The files are as follows:Log:
As you can see, initially the variable customersQuery, is loaded as usual by , and then mocked. Even after it is mocked,
foo
gets the un-mocked version of it. If I move customersQuery to the inner scope offoo
, the mock function is never called. Any help would be appreciated. Thank you.Node version v14.15.4 rewiremock 3.14.3. mocha 9.1.3