Skip to content

Commit

Permalink
chore: use jest.mocked helper in more tests (#13117)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB committed Aug 11, 2022
1 parent 240587b commit 24ed3b5
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 74 deletions.
4 changes: 2 additions & 2 deletions examples/typescript/__tests__/calc.test.ts
Expand Up @@ -7,8 +7,8 @@ jest.mock('../memory');
jest.mock('../sub');
jest.mock('../sum');

const mockSub = sub as jest.MockedFunction<typeof sub>;
const mockSum = sum as jest.MockedFunction<typeof sum>;
const mockSub = jest.mocked(sub);
const mockSum = jest.mocked(sum);
const MockMemory = Memory as jest.MockedClass<typeof Memory>;

describe('calc - mocks', () => {
Expand Down
14 changes: 6 additions & 8 deletions packages/jest-config/src/__tests__/normalize.test.ts
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-resolve/src/__mocks__/userResolver.d.ts
Expand Up @@ -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;
6 changes: 4 additions & 2 deletions packages/jest-resolve/src/__mocks__/userResolverAsync.d.ts
Expand Up @@ -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;
46 changes: 25 additions & 21 deletions packages/jest-resolve/src/__tests__/resolve.test.ts
Expand Up @@ -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();
Expand Down Expand Up @@ -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: '/',
Expand All @@ -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,
Expand All @@ -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}),
);

Expand Down Expand Up @@ -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: '/',
Expand All @@ -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,
Expand All @@ -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})),
);

Expand Down Expand Up @@ -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, {
Expand All @@ -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');
});
});

Expand Down Expand Up @@ -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, {
Expand All @@ -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),
);
Expand All @@ -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, {
Expand All @@ -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),
);
Expand Down
24 changes: 12 additions & 12 deletions packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts
Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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(
[
Expand All @@ -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(
Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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,
});
Expand Down

0 comments on commit 24ed3b5

Please sign in to comment.