NagRock / ts-mockito

Mocking library for TypeScript
MIT License
974 stars 93 forks source link

Possible to mock 'fs' and 'process.env' ? #165

Closed iangregsondev closed 4 years ago

iangregsondev commented 4 years ago

Hi,

Great library, i wasn't liking very much the mock api that jest gives you :-(

Although I was wondering if its possible to mock something from node_modules that is imported inside a class and not passed in via the constructor.

The 2 modules I am talking about is fs (from node), one of my classes uses it. Also another class, my config class, returns methods from process.env

for example, I have a getDatabaseConnectionString() which basically returns the env variables

DATABASE_CONNECTION_STRING so i.e.

process.env.DATABASE_CONNECTION_STRING

I have an internal private validate method on the SUT that ensures that all environment variables exist.

I was wondering if ts-mockito can mock FS and process.env ?

I am using NestJS so technically I could pass in FS on the constructor and then when testing i could override it with a mocked version but I was wonder if ts-mockito can do the same as what jest does i.e.

jest.mock("fs")

As I say, if it doesn't that i can work around this by just passing in fs in the constructor (using dependency injection) and override with a mock at test time but would be nice to know if ts-mockito can mock node_modules ?

The other thing is the process.env, this sounds kind of wrong to pass in the process in the constructor, i was wondering what everyone else is doing ? Actually process you do not import its a method that comes built-in from node.

fs and proces.env are just 2 problems i have right now :-) I know I am going to get another issue as I use log4js - which is also imported directly in a module that depends on it.

Any ideas or help really appreciated

Thanks

iangregsondev commented 4 years ago

Ok I noticed that i can spy on the real object. Real object being any node_module.

MalouNetlight commented 2 years ago

Just for whoever is wondering, an environment variable can be overwritten for a test. process.env is a global property and therefore, simply setting the value of the environment variable as follows will set it globally and thus during your test: process.env.DATABASE_CONNECTION_STRING = "my-connection-string"