Repository: skovhus/jest-codemods
Pull request #275 (2022-05-14 21:45:11)

Clean up mocking code a bit
... Rabbit hole after trying to upgrade chalk. https://github.com/facebook/jest/issues/12270

codecov[bot]: # [Codecov](https://codecov.io/gh/skovhus/jest-codemods/pull/275?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Kenneth+Skovhus) Report
> Merging [#275](https://codecov.io/gh/skovhus/jest-codemods/pull/275?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Kenneth+Skovhus) (797dc3a) into [main](https://codecov.io/gh/skovhus/jest-codemods/commit/ed93f320c2bd03ee27bf9277b6b45204ae9d31e3?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Kenneth+Skovhus) (ed93f32) will **decrease** coverage by `0.10%`.
> The diff coverage is `n/a`.

```diff
@@            Coverage Diff             @@
##             main     #275      +/-   ##
==========================================
- Coverage   92.29%   92.18%   -0.11%     
==========================================
  Files          26       26              
  Lines        1842     1842              
  Branches      381      381              
==========================================
- Hits         1700     1698       -2     
- Misses        101      102       +1     
- Partials       41       42       +1     
```


| [Impacted Files](https://codecov.io/gh/skovhus/jest-codemods/pull/275?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Kenneth+Skovhus) | Coverage Δ | |
|---|---|---|
| [src/utils/proxyquire.ts](https://codecov.io/gh/skovhus/jest-codemods/pull/275/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Kenneth+Skovhus#diff-c3JjL3V0aWxzL3Byb3h5cXVpcmUudHM=) | `88.13% <0.00%> (-3.39%)` | :arrow_down: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/skovhus/jest-codemods/pull/275?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Kenneth+Skovhus).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Kenneth+Skovhus)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/skovhus/jest-codemods/pull/275?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Kenneth+Skovhus). Last update [ed93f32...797dc3a](https://codecov.io/gh/skovhus/jest-codemods/pull/275?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Kenneth+Skovhus). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Kenneth+Skovhus).


Patch:
diff --git a/package.json b/package.json
index 7edfe4d..cfabc24 100644
--- a/package.json
+++ b/package.json
@@ -85,6 +85,7 @@
   },
   "jest": {
     "preset": "ts-jest",
+    "resetMocks": true,
     "collectCoverageFrom": [
       "src/**/*.ts"
     ],


Test patch:
diff --git a/src/cli/git-status.test.ts b/src/cli/git-status.test.ts
index 299a570..ace8d32 100644
--- a/src/cli/git-status.test.ts
+++ b/src/cli/git-status.test.ts
@@ -13,53 +13,47 @@ jest.setMock('is-git-clean', {
 // eslint-disable-next-line @typescript-eslint/no-var-requires
 const checkGitStatus = require('./git-status').default
 
-const _process: any = process
+beforeAll(() => {
+  jest.spyOn(console, 'log').mockImplementation()
+  jest.spyOn(console, 'warn').mockImplementation()
+  jest.spyOn(process, 'exit').mockImplementation()
+})
 
 it('does not exit and output any logs when git repo is clean', () => {
   gitStatusReturnValue = true
-  console.log = jest.fn()
-  _process.exit = jest.fn()
   checkGitStatus()
   expect(console.log).not.toHaveBeenCalled()
-  expect(_process.exit).not.toHaveBeenCalled()
+  expect(process.exit).not.toHaveBeenCalled()
 })
 
 it('does not exit and output any logs when not a git repo', () => {
   const err = new Error() as any
   err.stderr = 'Not a git repository'
   gitStatusReturnValue = err
-  console.log = jest.fn()
-  _process.exit = jest.fn()
   checkGitStatus()
   expect(console.log).not.toHaveBeenCalled()
-  expect(_process.exit).not.toHaveBeenCalled()
+  expect(process.exit).not.toHaveBeenCalled()
 })
 
 it('exits and output logs when git repo is dirty', () => {
   gitStatusReturnValue = false
-  console.log = jest.fn()
-  _process.exit = jest.fn()
   checkGitStatus()
   expect(console.log).toHaveBeenCalled()
-  expect(_process.exit).toHaveBeenCalled()
+  expect(process.exit).toHaveBeenCalled()
 })
 
 it('exits and output logs when git detection fail', () => {
   gitStatusReturnValue = new Error('bum')
-  console.log = jest.fn()
-  _process.exit = jest.fn()
   checkGitStatus()
   expect(console.log).toHaveBeenCalled()
-  expect(_process.exit).toHaveBeenCalled()
+  expect(process.exit).toHaveBeenCalled()
 })
 
 it('does not exit when git repo is dirty and force flag is given', () => {
   gitStatusReturnValue = false
-  console.log = jest.fn()
-  _process.exit = jest.fn()
   checkGitStatus(true)
   expect(console.log).toHaveBeenCalledWith(
     'WARNING: Git directory is not clean. Forcibly continuing.\n'
   )
-  expect(_process.exit).not.toHaveBeenCalled()
+  expect(process.exit).not.toHaveBeenCalled()
 })
diff --git a/src/cli/transformers.test.ts b/src/cli/transformers.test.ts
index 6de0c47..2ec8f1e 100644
--- a/src/cli/transformers.test.ts
+++ b/src/cli/transformers.test.ts
@@ -15,6 +15,10 @@ import {
   transformerDirectory,
 } from './transformers'
 
+beforeAll(() => {
+  jest.spyOn(console, 'log').mockImplementation()
+})
+
 it('finds transformer directory', () => {
   fs.lstatSync(transformerDirectory)
 })
@@ -25,7 +29,6 @@ it('finds jscodeshift executable', () => {
 
 it('runs jscodeshift for the given transformer', () => {
   execaReturnValue = { stderr: null }
-  console.log = jest.fn()
   executeTransformations({
     files: 'src',
     flags: {},
@@ -42,7 +45,6 @@ it('runs jscodeshift for the given transformer', () => {
 
 it('supports jscodeshift flags', () => {
   execaReturnValue = { stderr: null }
-  console.log = jest.fn()
   executeTransformations({
     files: 'folder',
     flags: { dry: true },
@@ -59,7 +61,6 @@ it('supports jscodeshift flags', () => {
 
 it('supports typescript parser', () => {
   execaReturnValue = { stderr: null }
-  console.log = jest.fn()
   executeTransformations({
     files: 'folder',
     flags: { dry: true },
@@ -76,7 +77,6 @@ it('supports typescript parser', () => {
 
 it('supports jscodeshift custom arguments', () => {
   execaReturnValue = { stderr: null }
-  console.log = jest.fn()
   executeTransformations({
     files: 'folder',
     flags: { dry: true },
@@ -95,7 +95,6 @@ it('supports jscodeshift custom arguments', () => {
 it('rethrows jscodeshift errors', () => {
   const transformerError = new Error('bum')
   execaReturnValue = { stderr: transformerError }
-  console.log = jest.fn()
   expect(() => {
     executeTransformations({
       files: 'src',
diff --git a/src/transformers/ava.test.ts b/src/transformers/ava.test.ts
index 9872ff7..94a115d 100644
--- a/src/transformers/ava.test.ts
+++ b/src/transformers/ava.test.ts
@@ -10,7 +10,7 @@ const wrappedPlugin = wrapPlugin(plugin)
 let consoleWarnings = []
 beforeEach(() => {
   consoleWarnings = []
-  console.warn = (v) => consoleWarnings.push(v)
+  jest.spyOn(console, 'warn').mockImplementation((v) => consoleWarnings.push(v))
 })
 
 function expectTransformation(source, expectedOutput, options = {}) {
diff --git a/src/transformers/chai-assert.test.ts b/src/transformers/chai-assert.test.ts
index 3f5f8d9..4d92ae2 100644
--- a/src/transformers/chai-assert.test.ts
+++ b/src/transformers/chai-assert.test.ts
@@ -10,7 +10,7 @@ const wrappedPlugin = wrapPlugin(plugin)
 let consoleWarnings = []
 beforeEach(() => {
   consoleWarnings = []
-  console.warn = (v) => consoleWarnings.push(v)
+  jest.spyOn(console, 'warn').mockImplementation((v) => consoleWarnings.push(v))
 })
 
 function expectTransformation(source, expectedOutput, options = {}) {
diff --git a/src/transformers/chai-should.test.ts b/src/transformers/chai-should.test.ts
index 4e329ec..f15671d 100644
--- a/src/transformers/chai-should.test.ts
+++ b/src/transformers/chai-should.test.ts
@@ -10,7 +10,7 @@ const wrappedPlugin = wrapPlugin(plugin)
 let consoleWarnings = []
 beforeEach(() => {
   consoleWarnings = []
-  console.warn = (v) => consoleWarnings.push(v)
+  jest.spyOn(console, 'warn').mockImplementation((v) => consoleWarnings.push(v))
 })
 
 function expectTransformation(source, expectedOutput) {
diff --git a/src/transformers/expect-js.test.ts b/src/transformers/expect-js.test.ts
index 8901dec..3ed9ea7 100644
--- a/src/transformers/expect-js.test.ts
+++ b/src/transformers/expect-js.test.ts
@@ -10,7 +10,7 @@ const wrappedPlugin = wrapPlugin(plugin)
 let consoleWarnings = []
 beforeEach(() => {
   consoleWarnings = []
-  console.warn = (v) => consoleWarnings.push(v)
+  jest.spyOn(console, 'warn').mockImplementation((v) => consoleWarnings.push(v))
 })
 
 function expectTransformation(source, expectedOutput, options = {}) {
diff --git a/src/transformers/expect.test.ts b/src/transformers/expect.test.ts
index 03ef4ba..39c9a02 100644
--- a/src/transformers/expect.test.ts
+++ b/src/transformers/expect.test.ts
@@ -10,7 +10,7 @@ const wrappedPlugin = wrapPlugin(plugin)
 let consoleWarnings = []
 beforeEach(() => {
   consoleWarnings = []
-  console.warn = (v) => consoleWarnings.push(v)
+  jest.spyOn(console, 'warn').mockImplementation((v) => consoleWarnings.push(v))
 })
 
 function expectTransformation(source, expectedOutput, options = {}) {
diff --git a/src/transformers/jasmine-globals.test.ts b/src/transformers/jasmine-globals.test.ts
index 397a5de..7783acb 100644
--- a/src/transformers/jasmine-globals.test.ts
+++ b/src/transformers/jasmine-globals.test.ts
@@ -10,7 +10,7 @@ let consoleWarnings = []
 
 beforeEach(() => {
   consoleWarnings = []
-  console.warn = (v) => consoleWarnings.push(v)
+  jest.spyOn(console, 'warn').mockImplementation((v) => consoleWarnings.push(v))
 })
 
 test('spyOn', () => {
diff --git a/src/transformers/mocha.test.ts b/src/transformers/mocha.test.ts
index 2b0f1de..ee3089a 100644
--- a/src/transformers/mocha.test.ts
+++ b/src/transformers/mocha.test.ts
@@ -7,7 +7,7 @@ const wrappedPlugin = wrapPlugin(plugin)
 let consoleWarnings = []
 beforeEach(() => {
   consoleWarnings = []
-  console.warn = (v) => consoleWarnings.push(v)
+  jest.spyOn(console, 'warn').mockImplementation((v) => consoleWarnings.push(v))
 })
 
 function expectTransformation(source, expectedOutput, options = {}) {
diff --git a/src/transformers/should.test.ts b/src/transformers/should.test.ts
index 7f48aa1..d258154 100644
--- a/src/transformers/should.test.ts
+++ b/src/transformers/should.test.ts
@@ -10,7 +10,7 @@ const wrappedPlugin = wrapPlugin(plugin)
 let consoleWarnings = []
 beforeEach(() => {
   consoleWarnings = []
-  console.warn = (v) => consoleWarnings.push(v)
+  jest.spyOn(console, 'warn').mockImplementation((v) => consoleWarnings.push(v))
 })
 
 function expectTransformation(source, expectedOutput) {
diff --git a/src/transformers/tape.test.ts b/src/transformers/tape.test.ts
index fd38a80..30aa82d 100644
--- a/src/transformers/tape.test.ts
+++ b/src/transformers/tape.test.ts
@@ -11,7 +11,7 @@ const wrappedPlugin = wrapPlugin(plugin)
 let consoleWarnings = []
 beforeEach(() => {
   consoleWarnings = []
-  console.warn = (v) => consoleWarnings.push(v)
+  jest.spyOn(console, 'warn').mockImplementation((v) => consoleWarnings.push(v))
 })
 
 function expectTransformation(source, expectedOutput, options = {}) {
diff --git a/src/utils/finale.test.ts b/src/utils/finale.test.ts
index e1cf63e..16e237d 100644
--- a/src/utils/finale.test.ts
+++ b/src/utils/finale.test.ts
@@ -9,7 +9,7 @@ chalk.level = 0
 let consoleWarnings = []
 beforeEach(() => {
   consoleWarnings = []
-  console.warn = (v) => consoleWarnings.push(v)
+  jest.spyOn(console, 'warn').mockImplementation((v) => consoleWarnings.push(v))
 })
 
 function testChanged(msg, source, expectedOutput, options = {}, expectedErrors = []) {
diff --git a/src/utils/proxyquire.test.ts b/src/utils/proxyquire.test.ts
index 70a9f0f..fcb4fef 100644
--- a/src/utils/proxyquire.test.ts
+++ b/src/utils/proxyquire.test.ts
@@ -1,10 +1,12 @@
 /* eslint-env jest */
 import jscodeshift from 'jscodeshift'
 
+import * as _logger from './logger'
 import proxyquireTransformer from './proxyquire'
 
-const mockedLogger = jest.fn()
-jest.mock('./logger', () => (args) => mockedLogger(args))
+jest.spyOn(_logger, 'default')
+const logger = _logger.default
+
 const j = jscodeshift
 const fileInfo = { path: 'a.test.js' }
 
@@ -24,7 +26,7 @@ it('rewrites proxyquire without noCallThru', () => {
         jest.mock('common/Foo', () => () => <div />);
         const { mapStateToProps, default: Page } = require('./PageContainer');
     `)
-  expect(mockedLogger).not.toHaveBeenCalled()
+  expect(logger).not.toHaveBeenCalled()
 })
 
 it('rewrites proxyquire with noCallThru', () => {
@@ -39,7 +41,7 @@ it('rewrites proxyquire with noCallThru', () => {
         jest.mock('common/Foo', () => () => <div />);
         const Page = require('./PageContainer');
     `)
-  expect(mockedLogger).not.toHaveBeenCalled()
+  expect(logger).not.toHaveBeenCalled()
 })
 
 it('rewrites proxyquire with require statement noCallThru', () => {
@@ -54,7 +56,7 @@ it('rewrites proxyquire with require statement noCallThru', () => {
         jest.mock('lib', () => () => {});
         const tracking = require('./tracking');
     `)
-  expect(mockedLogger).not.toHaveBeenCalled()
+  expect(logger).not.toHaveBeenCalled()
 })
 
 it('supports variable reference object', () => {
@@ -94,7 +96,7 @@ it('supports variable reference object', () => {
             t.end();
         });
     `)
-  expect(mockedLogger).not.toHaveBeenCalled()
+  expect(logger).not.toHaveBeenCalled()
 })
 
 it('supports empty noCallThru', () => {
@@ -108,7 +110,7 @@ it('supports empty noCallThru', () => {
         jest.mock('b', () => 'c');
         const a = require('a');
     `)
-  expect(mockedLogger).not.toHaveBeenCalled()
+  expect(logger).not.toHaveBeenCalled()
 })
 
 it('supports the `load` method', () => {
@@ -121,7 +123,7 @@ it('supports the `load` method', () => {
         jest.mock('b', () => 'c');
         const a = require('a');
     `)
-  expect(mockedLogger).not.toHaveBeenCalled()
+  expect(logger).not.toHaveBeenCalled()
 })
 
 it('supports a chained `noCallThru().load()` call', () => {
@@ -134,7 +136,7 @@ it('supports a chained `noCallThru().load()` call', () => {
         jest.mock('b', () => 'c');
         const a = require('a');
     `)
-  expect(mockedLogger).not.toHaveBeenCalled()
+  expect(logger).not.toHaveBeenCalled()
 })
 
 it('supports named imports scoped to the variable name', () => {
@@ -151,7 +153,7 @@ it('supports named imports scoped to the variable name', () => {
             const something = require('a');
         });
     `)
-  expect(mockedLogger).not.toHaveBeenCalled()
+  expect(logger).not.toHaveBeenCalled()
 })
 
 it('logs error when proxyquire mocks are not defined in the file', () => {
@@ -166,16 +168,7 @@ it('logs error when proxyquire mocks are not defined in the file', () => {
         import mockedDeps from './someFile';
         proxyquire.noCallThru()('./index', mockedDeps);
     `)
-  expect(mockedLogger).toHaveBeenCalled()
-})
-
-it('logs error when type of mock is not known', () => {
-  const ast = j(`
-        import proxyquire from 'proxyquire';
-        proxyquire.noCallThru()('./index', () => {});
-    `)
-  proxyquireTransformer(fileInfo, j, ast)
-  expect(mockedLogger).toHaveBeenCalled()
+  expect(logger).toHaveBeenCalled()
 })
 
 it('logs error with multiple proxyquire to same file', () => {
@@ -196,5 +189,5 @@ it('logs error with multiple proxyquire to same file', () => {
             '../page': mockedFailingRender,
         });
     `)
-  expect(mockedLogger).toHaveBeenCalled()
+  expect(logger).toHaveBeenCalled()
 })