Skip to content

Commit

Permalink
test(container-metadata): migrate tests from jest to vitest (#1170)
Browse files Browse the repository at this point in the history
* test(container-metadata): migrate tests from jest to vitest

* test(container-metadata): migrate tests from jest to vitest
  • Loading branch information
gperdomor authored Dec 12, 2024
1 parent 97a7f89 commit 48b0475
Show file tree
Hide file tree
Showing 13 changed files with 133 additions and 81 deletions.
2 changes: 1 addition & 1 deletion packages/container-metadata/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ Run `nx build container-metadata` to build the library.

## Running unit tests

Run `nx test container-metadata` to execute the unit tests via [Jest](https://jestjs.io).
Run `nx test container-metadata` to execute the unit tests via [Vitest](https://vitest.dev/).
2 changes: 1 addition & 1 deletion packages/container-metadata/eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module.exports = [
'@nx/dependency-checks': [
'error',
{
ignoredFiles: ['{projectRoot}/eslint.config.{js,cjs,mjs}'],
ignoredFiles: ['{projectRoot}/eslint.config.{js,cjs,mjs}', '{projectRoot}/vite.config.{js,ts,mjs,mts}'],
},
],
},
Expand Down
10 changes: 0 additions & 10 deletions packages/container-metadata/jest.config.ts

This file was deleted.

11 changes: 9 additions & 2 deletions packages/container-metadata/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
"sourceRoot": "packages/container-metadata/src",
"projectType": "library",
"tags": ["type:lib", "scope:nx-container"],
"// targets": "to see all targets run: nx show project container-metadata --web",
"targets": {}
"targets": {
"test": {
"executor": "@nx/vite:test",
"outputs": ["{options.reportsDirectory}"],
"options": {
"reportsDirectory": "../../coverage/packages/container-metadata"
}
}
}
}
34 changes: 10 additions & 24 deletions packages/container-metadata/src/lib/context.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,22 @@ import { ContextProxyFactory, RunnerContext } from '@nx-tools/ci-context';
import { Git } from '@nx-tools/ci-context/src/lib/utils/git';
import { Github } from '@nx-tools/ci-context/src/lib/utils/github';
import { getPosixName } from '@nx-tools/core';
import * as dotenv from 'dotenv';
import mockedEnv, { RestoreFn } from 'mocked-env';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { stubEnvsFromFile } from '../test-utils.spec';
import { Inputs, getContext, getInputs } from './context';

beforeEach(() => {
jest.clearAllMocks();
vi.resetAllMocks();
});

describe('getInputs', () => {
beforeEach(() => {
process.env = Object.keys(process.env).reduce((object, key) => {
process.env = Object.keys(process.env).reduce<NodeJS.ProcessEnv>((object, key) => {
if (!key.startsWith('INPUT_')) {
object[key] = process.env[key];
}
return object;
}, {} as NodeJS.ProcessEnv);
}, {});
});

// prettier-ignore
Expand Down Expand Up @@ -97,27 +95,16 @@ describe('getInputs', () => {
});

describe('getContext', () => {
let restore: RestoreFn;

beforeEach(() => {
jest.resetModules();
restore = mockedEnv(
{
...process.env,
...dotenv.parse(
fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures/event_create_branch.env'))
),
},
{ restore: true }
);
stubEnvsFromFile(path.join(__dirname, '..', '..', '__tests__', 'fixtures/event_create_branch.env'));
});

afterEach(() => {
restore();
vi.unstubAllEnvs();
});

it('workflow', async () => {
jest.spyOn(ContextProxyFactory, 'create').mockImplementation((): Promise<RunnerContext> => {
vi.spyOn(ContextProxyFactory, 'create').mockImplementation((): Promise<RunnerContext> => {
return Github.context();
});

Expand All @@ -127,10 +114,9 @@ describe('getContext', () => {
});

it('git', async () => {
jest.spyOn(Git, 'ref').mockResolvedValue('refs/heads/git-test');
jest.spyOn(Git, 'fullCommit').mockResolvedValue('git-test-sha');

jest.spyOn(ContextProxyFactory, 'create').mockImplementation((): Promise<RunnerContext> => {
vi.spyOn(Git, 'ref').mockResolvedValue('refs/heads/git-test');
vi.spyOn(Git, 'fullCommit').mockResolvedValue('git-test-sha');
vi.spyOn(ContextProxyFactory, 'create').mockImplementation((): Promise<RunnerContext> => {
return Git.context();
});

Expand Down
6 changes: 3 additions & 3 deletions packages/container-metadata/src/lib/flavor.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { logger } from '@nx-tools/core';
import { mockConsole } from '../test-utils.spec';
import { Flavor, Transform } from './flavor';

describe('transform', () => {
beforeAll(() => {
jest.spyOn(console, 'info').mockImplementation(() => true);
jest.spyOn(console, 'log').mockImplementation(() => true);
mockConsole();
});

afterAll(() => {
jest.clearAllMocks();
vi.restoreAllMocks();
});

// prettier-ignore
Expand Down
6 changes: 3 additions & 3 deletions packages/container-metadata/src/lib/image.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { logger } from '@nx-tools/core';
import { mockConsole } from '../test-utils.spec';
import { Image, Transform } from './image';

describe('transform', () => {
beforeAll(() => {
jest.spyOn(console, 'info').mockImplementation(() => true);
jest.spyOn(console, 'log').mockImplementation(() => true);
mockConsole();
});

afterAll(() => {
jest.clearAllMocks();
vi.restoreAllMocks();
});

// prettier-ignore
Expand Down
60 changes: 30 additions & 30 deletions packages/container-metadata/src/lib/meta.spec.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,43 @@
import { ContextProxyFactory, RepoMetadata, RepoProxyFactory, RunnerContext } from '@nx-tools/ci-context';
import { Github } from '@nx-tools/ci-context/src/lib/utils/github';
import { RepoMetadata, RepoProxyFactory } from '@nx-tools/ci-context';
import { logger } from '@nx-tools/core';
import { workspaceRoot } from '@nx/devkit';
import * as dotenv from 'dotenv';
import * as fs from 'node:fs';
import * as path from 'node:path';
import repoFixture from '../../__tests__/fixtures/repo.json';
import { mockConsole, stubEnvsFromFile } from '../test-utils.spec';
import { Inputs, getContext, getInputs } from './context';
import { Meta, Version } from './meta';

jest.spyOn(RepoProxyFactory, 'create').mockImplementation((): Promise<RepoMetadata> => {
return <Promise<RepoMetadata>>(repoFixture as unknown);
});
const ci = require('ci-info');

jest.spyOn(global.Date.prototype, 'toISOString').mockImplementation(() => {
return '2020-01-10T00:30:00.000Z';
});
beforeAll(() => {
mockConsole();

jest.mock('moment-timezone', () => {
return () => (jest.requireActual('moment-timezone') as typeof import('moment-timezone'))('2020-01-10T00:30:00.000Z');
});
vi.spyOn(ci, 'GITHUB_ACTIONS', 'get').mockReturnValue(true);

beforeAll(() => {
jest.spyOn(console, 'info').mockImplementation(() => true);
jest.spyOn(console, 'log').mockImplementation(() => true);
jest.spyOn(console, 'warn').mockImplementation(() => true);
vi.spyOn(RepoProxyFactory, 'create').mockImplementation((): Promise<RepoMetadata> => {
return <Promise<RepoMetadata>>(repoFixture as unknown);
});

vi.spyOn(global.Date.prototype, 'toISOString').mockImplementation(() => {
return '2020-01-10T00:30:00.000Z';
});

vi.useFakeTimers();
vi.setSystemTime(new Date('2020-01-10T00:30:00.000Z'));
});

afterAll(() => {
jest.clearAllMocks();
vi.useRealTimers();
vi.resetAllMocks();
});

beforeEach(() => {
jest.clearAllMocks();
Object.keys(process.env).forEach(function (key) {
if (key !== 'GITHUB_TOKEN' && key.startsWith('GITHUB_')) {
delete process.env[key];
}
});
jest.spyOn(ContextProxyFactory, 'create').mockImplementation((): Promise<RunnerContext> => {
return Github.context();
});

// workaround for https://github.com/nrwl/nx/issues/20330
const projectDir = `${workspaceRoot}/packages/container-metadata`;
Expand All @@ -62,6 +59,10 @@ describe('isRawStatement', () => {
});
});

const stubEnvs = (envFile: string) => {
stubEnvsFromFile(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile));
};

const tagsLabelsTest = async (
name: string,
envFile: string,
Expand All @@ -71,7 +72,7 @@ const tagsLabelsTest = async (
exLabels: Array<string>,
exAnnotations: Array<string> | undefined
) => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile)));
stubEnvs(envFile);
const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({ ...getInputs({}), ...inputs }, await getContext(), repo, logger);

Expand Down Expand Up @@ -2984,11 +2985,11 @@ describe('pr-head-sha', () => {
]
],
])('given %p with %p event', async (name: string, envFile: string, inputs: Inputs, exVersion: Version, exTags: Array<string>, exLabelsAnnotations: Array<string>) => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile)));
process.env.DOCKER_METADATA_PR_HEAD_SHA = 'true';
stubEnvs(envFile);
vi.stubEnv('DOCKER_METADATA_PR_HEAD_SHA', "true");

const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo, logger);
const meta = new Meta({ ...getInputs({}), ...inputs }, await getContext(), repo, logger);

const version = meta.version;
expect(version).toEqual(exVersion);
Expand Down Expand Up @@ -4017,7 +4018,7 @@ describe('json', () => {
}
]
])('given %p with %p event', async (name: string, envFile: string, inputs: Inputs, exJSON: unknown) => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile)));
stubEnvs(envFile);

const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo, logger);
Expand Down Expand Up @@ -4531,7 +4532,7 @@ describe('bakeFile', () => {
}
]
])('given %p with %p event', async (name: string, envFile: string, inputs: Inputs, exBakeTags: unknown, exBakeLabels: unknown, exBakeAnnotations: unknown) => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile)));
stubEnvs(envFile);

const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo, logger);
Expand Down Expand Up @@ -4593,7 +4594,7 @@ describe('bakeFileTagsLabels', () => {
}
]
])('given %p with %p event', async (name: string, envFile: string, inputs: Inputs, exBakeDefinition: unknown) => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile)));
stubEnvs(envFile);

const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo, logger);
Expand Down Expand Up @@ -4637,8 +4638,7 @@ describe('sepTags', () => {
"user/app:dev,user/app:my,user/app:custom,user/app:tags"
]
])('given %p with %p event', async (name: string, envFile: string, inputs: Inputs, expTags: string) => {

process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile)));
stubEnvs(envFile);

const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo, logger);
Expand Down
6 changes: 3 additions & 3 deletions packages/container-metadata/src/lib/tag.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { logger } from '@nx-tools/core';
import { mockConsole } from '../test-utils.spec';
import { DefaultPriorities, Parse, RefEvent, ShaFormat, Tag, Transform, Type } from './tag';

beforeAll(() => {
jest.spyOn(console, 'info').mockImplementation(() => true);
jest.spyOn(console, 'log').mockImplementation(() => true);
mockConsole();
});

afterAll(() => {
jest.clearAllMocks();
vi.restoreAllMocks();
});

describe('transform', () => {
Expand Down
20 changes: 20 additions & 0 deletions packages/container-metadata/src/test-utils.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import * as dotenv from 'dotenv';
import * as fs from 'node:fs';

export const mockConsole = () => {
vi.spyOn(console, 'info').mockImplementation(() => true);
vi.spyOn(console, 'log').mockImplementation(() => true);
vi.spyOn(console, 'warn').mockImplementation(() => true);
};

export const stubEnvsFromFile = (path: string) => {
const envs = dotenv.parse(fs.readFileSync(path));

Object.keys(envs).forEach((key) => {
vi.stubEnv(key, envs[key]);
});
};

it('should work', () => {
expect(true).toBeTruthy();
});
15 changes: 14 additions & 1 deletion packages/container-metadata/tsconfig.lib.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,18 @@
"path": "../ci-context/tsconfig.lib.json"
}
],
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
"exclude": [
"vite.config.ts",
"vite.config.mts",
"vitest.config.ts",
"vitest.config.mts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.test.tsx",
"src/**/*.spec.tsx",
"src/**/*.test.js",
"src/**/*.spec.js",
"src/**/*.test.jsx",
"src/**/*.spec.jsx"
]
}
22 changes: 19 additions & 3 deletions packages/container-metadata/tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./out-tsc/jest",
"types": ["jest", "node"],
"outDir": "./out-tsc/vitest",
"types": ["vitest/globals", "vitest/importMeta", "vite/client", "node", "vitest"],
"resolveJsonModule": true
},
"include": ["jest.config.ts", "src/**/*.test.ts", "src/**/*.spec.ts", "src/**/*.d.ts"],
"include": [
"vite.config.ts",
"vite.config.mts",
"vitest.config.ts",
"vitest.config.mts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.test.tsx",
"src/**/*.spec.tsx",
"src/**/*.test.js",
"src/**/*.spec.js",
"src/**/*.test.jsx",
"src/**/*.spec.jsx",
"src/**/*.d.ts",
"__tests__/**/*.env",
"__tests__/**/*.json"
],
"references": [
{
"path": "./tsconfig.lib.json"
Expand Down
20 changes: 20 additions & 0 deletions packages/container-metadata/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { defineConfig } from 'vite';

export default defineConfig({
root: __dirname,
cacheDir: '../../node_modules/.vite/packages/container-metadata',
plugins: [],
// Uncomment this if you are using workers.
// worker: {
// plugins: [ nxViteTsPaths() ],
// },
test: {
watch: false,
globals: true,
environment: 'node',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
reporters: ['default'],
coverage: { reportsDirectory: '../../coverage/packages/container-metadata', provider: 'v8' },
pool: 'forks',
},
});

0 comments on commit 48b0475

Please sign in to comment.