From 24ed3b5ecb419c023ee6fdbc838f07cc028fc007 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Thu, 11 Aug 2022 10:34:17 +0200 Subject: [PATCH] chore: use `jest.mocked` helper in more tests (#13117) --- examples/typescript/__tests__/calc.test.ts | 4 +- .../src/__tests__/normalize.test.ts | 14 ++--- .../src/__mocks__/userResolver.d.ts | 4 +- .../src/__mocks__/userResolverAsync.d.ts | 6 +- .../src/__tests__/resolve.test.ts | 46 ++++++++------- .../src/__tests__/InlineSnapshots.test.ts | 24 ++++---- .../jest-snapshot/src/__tests__/utils.test.ts | 56 ++++++++++--------- .../src/__tests__/getCallsite.test.ts | 4 +- 8 files changed, 84 insertions(+), 74 deletions(-) diff --git a/examples/typescript/__tests__/calc.test.ts b/examples/typescript/__tests__/calc.test.ts index ef5039e6acdd..cb9bd0210549 100644 --- a/examples/typescript/__tests__/calc.test.ts +++ b/examples/typescript/__tests__/calc.test.ts @@ -7,8 +7,8 @@ jest.mock('../memory'); jest.mock('../sub'); jest.mock('../sum'); -const mockSub = sub as jest.MockedFunction; -const mockSum = sum as jest.MockedFunction; +const mockSub = jest.mocked(sub); +const mockSum = jest.mocked(sum); const MockMemory = Memory as jest.MockedClass; describe('calc - mocks', () => { diff --git a/packages/jest-config/src/__tests__/normalize.test.ts b/packages/jest-config/src/__tests__/normalize.test.ts index 39f4c0da60a1..ac1b24a69e8f 100644 --- a/packages/jest-config/src/__tests__/normalize.test.ts +++ b/packages/jest-config/src/__tests__/normalize.test.ts @@ -63,7 +63,7 @@ beforeEach(() => { }); afterEach(() => { - (console.warn as unknown as jest.SpyInstance).mockRestore(); + jest.mocked(console.warn).mockRestore(); }); it('picks an id based on the rootDir', async () => { @@ -148,7 +148,7 @@ describe('rootDir', () => { describe('automock', () => { it('falsy automock is not overwritten', async () => { - (console.warn as unknown as jest.SpyInstance).mockImplementation(() => {}); + jest.mocked(console.warn).mockImplementation(() => {}); const {options} = await normalize( { automock: false, @@ -1639,9 +1639,7 @@ describe('testPathPattern', () => { const {options} = await normalize(initialOptions, argv); expect(options.testPathPattern).toBe(''); - expect( - (console.log as unknown as jest.SpyInstance).mock.calls[0][0], - ).toMatchSnapshot(); + expect(jest.mocked(console.log).mock.calls[0][0]).toMatchSnapshot(); }); it(`joins multiple ${opt.name} if set`, async () => { @@ -1783,7 +1781,7 @@ describe('cwd', () => { }); it('is not lost if the config has its own cwd property', async () => { - (console.warn as unknown as jest.SpyInstance).mockImplementation(() => {}); + jest.mocked(console.warn).mockImplementation(() => {}); const {options} = await normalize( { cwd: '/tmp/config-sets-cwd-itself', @@ -1851,7 +1849,7 @@ describe('displayName', () => { describe('testTimeout', () => { it('should return timeout value if defined', async () => { - (console.warn as unknown as jest.SpyInstance).mockImplementation(() => {}); + jest.mocked(console.warn).mockImplementation(() => {}); const {options} = await normalize( {rootDir: '/root/', testTimeout: 1000}, {} as Config.Argv, @@ -2001,7 +1999,7 @@ describe('shards', () => { describe('logs a deprecation warning', () => { beforeEach(() => { - (console.warn as unknown as jest.SpyInstance).mockImplementation(() => {}); + jest.mocked(console.warn).mockImplementation(() => {}); }); test("when 'browser' option is passed", async () => { diff --git a/packages/jest-resolve/src/__mocks__/userResolver.d.ts b/packages/jest-resolve/src/__mocks__/userResolver.d.ts index 8d6bd2c26306..232bff738881 100644 --- a/packages/jest-resolve/src/__mocks__/userResolver.d.ts +++ b/packages/jest-resolve/src/__mocks__/userResolver.d.ts @@ -5,8 +5,8 @@ * LICENSE file in the root directory of this source tree. */ -import type {Resolver} from '../defaultResolver'; +import type {SyncResolver} from '../defaultResolver'; -declare const userResolver: Resolver; +declare const userResolver: SyncResolver; export default userResolver; diff --git a/packages/jest-resolve/src/__mocks__/userResolverAsync.d.ts b/packages/jest-resolve/src/__mocks__/userResolverAsync.d.ts index 8c23f0f74fda..b38bfb5296b9 100644 --- a/packages/jest-resolve/src/__mocks__/userResolverAsync.d.ts +++ b/packages/jest-resolve/src/__mocks__/userResolverAsync.d.ts @@ -5,9 +5,11 @@ * LICENSE file in the root directory of this source tree. */ -import type {Resolver} from '../defaultResolver'; +import type {AsyncResolver} from '../defaultResolver'; // todo: can be replaced with jest.MockedFunction -declare const userResolver: Resolver; +declare const userResolver: { + async: AsyncResolver; +}; export default userResolver; diff --git a/packages/jest-resolve/src/__tests__/resolve.test.ts b/packages/jest-resolve/src/__tests__/resolve.test.ts index 3143c9c45e6c..eb6d3c3cd7d3 100644 --- a/packages/jest-resolve/src/__tests__/resolve.test.ts +++ b/packages/jest-resolve/src/__tests__/resolve.test.ts @@ -31,11 +31,13 @@ jest.mock('resolve', () => { return m; }); +const mockUserResolver = jest.mocked(userResolver); +const mockUserResolverAsync = jest.mocked(userResolverAsync); const mockResolveSync = jest.mocked(resolveSync); beforeEach(() => { - userResolver.mockClear(); - userResolverAsync.async.mockClear(); + mockUserResolver.mockClear(); + mockUserResolverAsync.async.mockClear(); mockResolveSync.mockClear(); Resolver.clearDefaultResolverCache(); @@ -104,7 +106,7 @@ describe('findNodeModule', () => { .map(p => path.resolve(resolvedCwd, p)) : null; - userResolver.mockImplementation(() => 'module'); + mockUserResolver.mockImplementation(() => 'module'); const newPath = Resolver.findNodeModule('test', { basedir: '/', @@ -116,8 +118,8 @@ describe('findNodeModule', () => { }); expect(newPath).toBe('module'); - expect(userResolver.mock.calls[0][0]).toBe('test'); - expect(userResolver.mock.calls[0][1]).toStrictEqual({ + expect(mockUserResolver.mock.calls[0][0]).toBe('test'); + expect(mockUserResolver.mock.calls[0][1]).toStrictEqual({ basedir: '/', conditions: ['conditions, woooo'], defaultResolver, @@ -132,7 +134,7 @@ describe('findNodeModule', () => { const packageFilter = jest.fn(); // A resolver that delegates to defaultResolver with a packageFilter implementation - userResolver.mockImplementation((request, opts) => + mockUserResolver.mockImplementation((request, opts) => opts.defaultResolver(request, {...opts, packageFilter}), ); @@ -309,7 +311,7 @@ describe('findNodeModuleAsync', () => { .map(p => path.resolve(resolvedCwd, p)) : null; - userResolverAsync.async.mockImplementation(() => Promise.resolve('module')); + mockUserResolverAsync.async.mockResolvedValue('module'); const newPath = await Resolver.findNodeModuleAsync('test', { basedir: '/', @@ -321,8 +323,8 @@ describe('findNodeModuleAsync', () => { }); expect(newPath).toBe('module'); - expect(userResolverAsync.async.mock.calls[0][0]).toBe('test'); - expect(userResolverAsync.async.mock.calls[0][1]).toStrictEqual({ + expect(mockUserResolverAsync.async.mock.calls[0][0]).toBe('test'); + expect(mockUserResolverAsync.async.mock.calls[0][1]).toStrictEqual({ basedir: '/', conditions: ['conditions, woooo'], defaultResolver, @@ -337,7 +339,7 @@ describe('findNodeModuleAsync', () => { const packageFilter = jest.fn(); // A resolver that delegates to defaultResolver with a packageFilter implementation - userResolverAsync.async.mockImplementation((request, opts) => + mockUserResolverAsync.async.mockImplementation((request, opts) => Promise.resolve(opts.defaultResolver(request, {...opts, packageFilter})), ); @@ -445,7 +447,7 @@ describe('resolveModule', () => { }); it('custom resolver can resolve node modules', () => { - userResolver.mockImplementation(() => 'module'); + mockUserResolver.mockImplementation(() => 'module'); const moduleMap = ModuleMap.create('/'); const resolver = new Resolver(moduleMap, { @@ -455,8 +457,8 @@ describe('resolveModule', () => { const src = require.resolve('../'); resolver.resolveModule(src, 'fs'); - expect(userResolver).toHaveBeenCalled(); - expect(userResolver.mock.calls[0][0]).toBe('fs'); + expect(mockUserResolver).toHaveBeenCalled(); + expect(mockUserResolver.mock.calls[0][0]).toBe('fs'); }); }); @@ -559,7 +561,7 @@ describe('resolveModuleAsync', () => { describe('getMockModule', () => { it('is possible to use custom resolver to resolve deps inside mock modules with moduleNameMapper', () => { - userResolver.mockImplementation(() => 'module'); + mockUserResolver.mockImplementation(() => 'module'); const moduleMap = ModuleMap.create('/'); const resolver = new Resolver(moduleMap, { @@ -575,9 +577,9 @@ describe('getMockModule', () => { const src = require.resolve('../'); resolver.getMockModule(src, 'dependentModule'); - expect(userResolver).toHaveBeenCalled(); - expect(userResolver.mock.calls[0][0]).toBe('dependentModule'); - expect(userResolver.mock.calls[0][1]).toHaveProperty( + expect(mockUserResolver).toHaveBeenCalled(); + expect(mockUserResolver.mock.calls[0][0]).toBe('dependentModule'); + expect(mockUserResolver.mock.calls[0][1]).toHaveProperty( 'basedir', path.dirname(src), ); @@ -586,7 +588,7 @@ describe('getMockModule', () => { describe('getMockModuleAsync', () => { it('is possible to use custom resolver to resolve deps inside mock modules with moduleNameMapper', async () => { - userResolverAsync.async.mockImplementation(() => Promise.resolve('module')); + mockUserResolverAsync.async.mockResolvedValue('module'); const moduleMap = ModuleMap.create('/'); const resolver = new Resolver(moduleMap, { @@ -603,9 +605,11 @@ describe('getMockModuleAsync', () => { await resolver.resolveModuleAsync(src, 'dependentModule'); - expect(userResolverAsync.async).toHaveBeenCalled(); - expect(userResolverAsync.async.mock.calls[0][0]).toBe('dependentModule'); - expect(userResolverAsync.async.mock.calls[0][1]).toHaveProperty( + expect(mockUserResolverAsync.async).toHaveBeenCalled(); + expect(mockUserResolverAsync.async.mock.calls[0][0]).toBe( + 'dependentModule', + ); + expect(mockUserResolverAsync.async.mock.calls[0][1]).toHaveProperty( 'basedir', path.dirname(src), ); diff --git a/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts b/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts index 9be98e67ff3f..304b098301c4 100644 --- a/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts +++ b/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts @@ -30,9 +30,9 @@ jest.mock('prettier', () => { return mockPrettier; }); -let dir; +let dir: string; beforeEach(() => { - (prettier.resolveConfig.sync as jest.Mock).mockReset(); + jest.mocked(prettier.resolveConfig.sync).mockReset(); }); beforeEach(() => { @@ -262,7 +262,7 @@ test.each([['babel'], ['flow'], ['typescript']])( const filename = path.join(dir, 'my.test.js'); fs.writeFileSync(filename, 'expect(1).toMatchInlineSnapshot(`2`);\n'); - (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({parser}); + jest.mocked(prettier.resolveConfig.sync).mockReturnValue({parser}); saveInlineSnapshots( [ @@ -275,7 +275,7 @@ test.each([['babel'], ['flow'], ['typescript']])( ); expect( - (prettier.resolveConfig.sync as jest.Mock).mock.results[0].value, + jest.mocked(prettier.resolveConfig.sync).mock.results[0].value, ).toEqual({parser}); expect(fs.readFileSync(filename, 'utf-8')).toBe( @@ -381,7 +381,7 @@ test('saveInlineSnapshots() uses escaped backticks', () => { test('saveInlineSnapshots() works with non-literals in expect call', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync(filename, "expect({a: 'a'}).toMatchInlineSnapshot();\n"); - (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ + jest.mocked(prettier.resolveConfig.sync).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); @@ -409,7 +409,7 @@ test('saveInlineSnapshots() indents multi-line snapshots with spaces', () => { " expect({a: 'a'}).toMatchInlineSnapshot();\n" + '});\n', ); - (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ + jest.mocked(prettier.resolveConfig.sync).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); @@ -451,7 +451,7 @@ test('saveInlineSnapshots() does not re-indent error snapshots', () => { " expect({a: 'a'}).toMatchInlineSnapshot();\n" + '});\n', ); - (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ + jest.mocked(prettier.resolveConfig.sync).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); @@ -500,7 +500,7 @@ test('saveInlineSnapshots() does not re-indent already indented snapshots', () = ' `);\n' + '});\n', ); - (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ + jest.mocked(prettier.resolveConfig.sync).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); @@ -541,7 +541,7 @@ test('saveInlineSnapshots() indents multi-line snapshots with tabs', () => { " expect({a: 'a'}).toMatchInlineSnapshot();\n" + '});\n', ); - (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ + jest.mocked(prettier.resolveConfig.sync).mockReturnValue({ bracketSpacing: false, singleQuote: true, useTabs: true, @@ -574,7 +574,7 @@ test('saveInlineSnapshots() indents snapshots after prettier reformats', () => { filename, "it('is a test', () => expect({a: 'a'}).toMatchInlineSnapshot());\n", ); - (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ + jest.mocked(prettier.resolveConfig.sync).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); @@ -605,7 +605,7 @@ test('saveInlineSnapshots() does not indent empty lines', () => { filename, "it('is a test', () => expect(`hello\n\nworld`).toMatchInlineSnapshot());\n", ); - (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ + jest.mocked(prettier.resolveConfig.sync).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); @@ -639,7 +639,7 @@ test('saveInlineSnapshots() indents awaited snapshots with spaces', () => { ' await expect(a).resolves.toMatchInlineSnapshot();\n' + '});\n', ); - (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ + jest.mocked(prettier.resolveConfig.sync).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); diff --git a/packages/jest-snapshot/src/__tests__/utils.test.ts b/packages/jest-snapshot/src/__tests__/utils.test.ts index 182cd5d2723e..3f918a3cbeba 100644 --- a/packages/jest-snapshot/src/__tests__/utils.test.ts +++ b/packages/jest-snapshot/src/__tests__/utils.test.ts @@ -72,9 +72,9 @@ test('saveSnapshotFile() works with \r', () => { test('getSnapshotData() throws when no snapshot version', () => { const filename = path.join(__dirname, 'old-snapshot.snap'); - (fs.readFileSync as jest.Mock).mockImplementation( - () => 'exports[`myKey`] = `
\n
`;\n', - ); + jest + .mocked(fs.readFileSync) + .mockImplementation(() => 'exports[`myKey`] = `
\n
`;\n'); const update = 'none'; expect(() => getSnapshotData(filename, update)).toThrowError( @@ -89,11 +89,13 @@ test('getSnapshotData() throws when no snapshot version', () => { test('getSnapshotData() throws for older snapshot version', () => { const filename = path.join(__dirname, 'old-snapshot.snap'); - (fs.readFileSync as jest.Mock).mockImplementation( - () => - `// Jest Snapshot v0.99, ${SNAPSHOT_GUIDE_LINK}\n\n` + - 'exports[`myKey`] = `
\n
`;\n', - ); + jest + .mocked(fs.readFileSync) + .mockImplementation( + () => + `// Jest Snapshot v0.99, ${SNAPSHOT_GUIDE_LINK}\n\n` + + 'exports[`myKey`] = `
\n
`;\n', + ); const update = 'none'; expect(() => getSnapshotData(filename, update)).toThrowError( @@ -110,11 +112,13 @@ test('getSnapshotData() throws for older snapshot version', () => { test('getSnapshotData() throws for newer snapshot version', () => { const filename = path.join(__dirname, 'old-snapshot.snap'); - (fs.readFileSync as jest.Mock).mockImplementation( - () => - `// Jest Snapshot v2, ${SNAPSHOT_GUIDE_LINK}\n\n` + - 'exports[`myKey`] = `
\n
`;\n', - ); + jest + .mocked(fs.readFileSync) + .mockImplementation( + () => + `// Jest Snapshot v2, ${SNAPSHOT_GUIDE_LINK}\n\n` + + 'exports[`myKey`] = `
\n
`;\n', + ); const update = 'none'; expect(() => getSnapshotData(filename, update)).toThrowError( @@ -131,9 +135,9 @@ test('getSnapshotData() throws for newer snapshot version', () => { test('getSnapshotData() does not throw for when updating', () => { const filename = path.join(__dirname, 'old-snapshot.snap'); - (fs.readFileSync as jest.Mock).mockImplementation( - () => 'exports[`myKey`] = `
\n
`;\n', - ); + jest + .mocked(fs.readFileSync) + .mockImplementation(() => 'exports[`myKey`] = `
\n
`;\n'); const update = 'all'; expect(() => getSnapshotData(filename, update)).not.toThrow(); @@ -141,9 +145,9 @@ test('getSnapshotData() does not throw for when updating', () => { test('getSnapshotData() marks invalid snapshot dirty when updating', () => { const filename = path.join(__dirname, 'old-snapshot.snap'); - (fs.readFileSync as jest.Mock).mockImplementation( - () => 'exports[`myKey`] = `
\n
`;\n', - ); + jest + .mocked(fs.readFileSync) + .mockImplementation(() => 'exports[`myKey`] = `
\n
`;\n'); const update = 'all'; expect(getSnapshotData(filename, update)).toMatchObject({dirty: true}); @@ -151,11 +155,13 @@ test('getSnapshotData() marks invalid snapshot dirty when updating', () => { test('getSnapshotData() marks valid snapshot not dirty when updating', () => { const filename = path.join(__dirname, 'old-snapshot.snap'); - (fs.readFileSync as jest.Mock).mockImplementation( - () => - `// Jest Snapshot v${SNAPSHOT_VERSION}, ${SNAPSHOT_GUIDE_LINK}\n\n` + - 'exports[`myKey`] = `
\n
`;\n', - ); + jest + .mocked(fs.readFileSync) + .mockImplementation( + () => + `// Jest Snapshot v${SNAPSHOT_VERSION}, ${SNAPSHOT_GUIDE_LINK}\n\n` + + 'exports[`myKey`] = `
\n
`;\n', + ); const update = 'all'; expect(getSnapshotData(filename, update)).toMatchObject({dirty: false}); @@ -164,7 +170,7 @@ test('getSnapshotData() marks valid snapshot not dirty when updating', () => { test('escaping', () => { const filename = path.join(__dirname, 'escaping.snap'); const data = '"\'\\'; - const writeFileSync = fs.writeFileSync as jest.Mock; + const writeFileSync = jest.mocked(fs.writeFileSync); writeFileSync.mockReset(); saveSnapshotFile({key: data}, filename); diff --git a/packages/jest-source-map/src/__tests__/getCallsite.test.ts b/packages/jest-source-map/src/__tests__/getCallsite.test.ts index 0482b12f7323..fed6ab25e748 100644 --- a/packages/jest-source-map/src/__tests__/getCallsite.test.ts +++ b/packages/jest-source-map/src/__tests__/getCallsite.test.ts @@ -30,7 +30,7 @@ describe('getCallsite', () => { }); test('ignores errors when fs throws', () => { - (fs.readFileSync as jest.Mock).mockImplementation(() => { + jest.mocked(fs.readFileSync).mockImplementation(() => { throw new Error('Mock error'); }); @@ -43,7 +43,7 @@ describe('getCallsite', () => { }); test('reads source map file to determine line and column', () => { - (fs.readFileSync as jest.Mock).mockImplementation(() => + jest.mocked(fs.readFileSync).mockImplementation(() => JSON.stringify({ file: 'file.js', mappings: 'AAAA,OAAO,MAAM,KAAK,GAAG,QAAd',