level_0
int64 0
10k
| index
int64 0
0
| repo_id
stringlengths 22
152
| file_path
stringlengths 41
203
| content
stringlengths 11
11.5M
|
---|---|---|---|---|
5,307 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-5034-input-with-index-signature.test.ts | import {
inferRouterInputs,
inferRouterOutputs,
initTRPC,
Overwrite,
Simplify,
} from '@trpc/server';
import * as z from 'zod';
export function hardcodedExample() {
return async (data?: unknown) => {
return data as { [x: string]: unknown; name: string };
};
}
const t = initTRPC.create();
const symbol = Symbol('symbol');
const appRouter = t.router({
inputWithIndexSignature: t.procedure
.input(hardcodedExample())
.query(({ input }) => input),
inputWithIndexSignatureAndMiddleware: t.procedure
.input(hardcodedExample())
.use((opts) => opts.next())
.query(({ input }) => input),
normalInput: t.procedure
.input(z.object({ name: z.string() }))
.query(({ input }) => {
return input;
}),
middlewareWithSymbolKey: t.procedure
.use((opts) =>
opts.next({
ctx: {
foo: 'bar',
[symbol]: true,
} as const,
}),
)
.query((opts) => {
expectTypeOf(opts.ctx).toMatchTypeOf<{
foo: 'bar';
[symbol]: true;
}>();
return opts.ctx;
}),
});
type AppRouter = typeof appRouter;
describe('inferRouterInputs/inferRouterOutputs', () => {
type AppRouterInputs = inferRouterInputs<AppRouter>;
type AppRouterOutputs = inferRouterOutputs<AppRouter>;
test('input type with a known key and an index signature', async () => {
type Input = AppRouterInputs['inputWithIndexSignature'];
type Output = AppRouterOutputs['inputWithIndexSignature'];
expectTypeOf<Input>().toEqualTypeOf<{
[x: string]: unknown;
name: string;
}>();
expectTypeOf<Output>().toEqualTypeOf<{
[x: string]: unknown;
name: string;
}>();
});
test('input type with a known key and an index signature and middleware', async () => {
type Input = AppRouterInputs['inputWithIndexSignatureAndMiddleware'];
type Output = AppRouterOutputs['inputWithIndexSignatureAndMiddleware'];
expectTypeOf<Input>().toEqualTypeOf<{
[x: string]: unknown;
name: string;
}>();
expectTypeOf<Output>().toEqualTypeOf<{
[x: string]: unknown;
name: string;
}>();
});
test('normal input as sanity check', async () => {
type Input = AppRouterInputs['normalInput'];
type Output = AppRouterOutputs['normalInput'];
expectTypeOf<Input>().toEqualTypeOf<{ name: string }>();
expectTypeOf<Output>().toEqualTypeOf<{ name: string }>();
});
test('middleware with symbol key', async () => {
type Input = AppRouterInputs['middlewareWithSymbolKey'];
type Output = AppRouterOutputs['middlewareWithSymbolKey'];
expectTypeOf<Output>().toEqualTypeOf<{
foo: 'bar';
// symbol is stripped as part of SerializeObject
}>();
});
test('Overwrite util', () => {
type A = {
a: string;
};
type B = {
b: string;
[symbol]: true;
};
type C = {
a: number;
c: string;
};
type AB = Overwrite<A, B>;
type ABC = Overwrite<AB, C>;
expectTypeOf<AB>().toEqualTypeOf<{
a: string;
b: string;
[symbol]: true;
}>();
expectTypeOf<ABC>().toEqualTypeOf<{
a: number;
b: string;
c: string;
[symbol]: true;
}>();
});
});
|
5,308 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-5037-context-inference.test.ts | import {
inferRouterOutputs,
initTRPC,
ProcedureBuilder,
ProcedureParams,
TRPCError,
} from '@trpc/server';
import { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
import { z } from 'zod';
/**
* See @sentry/node trpc middleware:
* https://github.com/getsentry/sentry-javascript/blob/6d424571e3cd5e99991b711f4e23d773e321e294/packages/node/src/handlers.ts#L328
*/
interface TrpcMiddlewareArguments<T> {
path: string;
type: string;
next: () => T;
rawInput: unknown;
}
/**
* See @sentry/node trpc middleware:
* https://github.com/getsentry/sentry-javascript/blob/6d424571e3cd5e99991b711f4e23d773e321e294/packages/node/src/handlers.ts#L328
*/
function sentryTrpcMiddleware(_options: any) {
return function <T>({
path,
type,
next,
rawInput,
}: TrpcMiddlewareArguments<T>): T {
path;
type;
next;
rawInput;
// This function is effectively what @sentry/node does to provide its trpc middleware.
return null as any as T;
};
}
type Context = {
some: 'prop';
};
describe('context inference w/ middlewares', () => {
test('a base procedure using a generically constructed middleware should be extensible using another middleware', async () => {
const t = initTRPC.context<Context>().create();
const baseMiddleware = t.middleware(sentryTrpcMiddleware({ foo: 'bar' }));
const someMiddleware = t.middleware(async (opts) => {
return opts.next({
ctx: {
object: {
a: 'b',
},
},
});
});
const baseProcedure = t.procedure.use(baseMiddleware);
const bazQuxProcedure = baseProcedure.use(someMiddleware);
const appRouter = t.router({
foo: bazQuxProcedure.input(z.string()).query(({ ctx }) => ctx),
});
type Output = inferRouterOutputs<typeof appRouter>['foo'];
expectTypeOf<Output>().toEqualTypeOf<{
object: { a: string };
some: 'prop';
}>();
});
test('using generically constructed tRPC instance should have correctly inferred context', () => {
interface CreateInnerContextOptions
extends Partial<CreateFastifyContextOptions> {}
async function createInternalContext<T>(
createContextInner: (opts?: CreateInnerContextOptions) => T,
opts: any,
) {
const contextInner = createContextInner();
return {
...contextInner,
req: opts.req,
res: opts.res,
};
}
type LocalContext<T> = Awaited<ReturnType<typeof createInternalContext<T>>>;
type Context2<T> = T extends infer R ? LocalContext<R> : never;
function makeTRPC<T extends object>(
config?: Parameters<typeof initTRPC.create>[0],
) {
const t = initTRPC.context<Context2<T>>().create({
errorFormatter(error) {
return config?.errorFormatter?.(error) ?? error.shape;
},
});
function withAuth2<T extends ProcedureParams>(
builder: ProcedureBuilder<T>,
) {
return builder.use(async (opts) => {
if (!(opts.ctx as any).req) {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: 'missing req object',
});
}
try {
return opts.next({
ctx: {
auth: {
stuff: 'here',
},
},
});
} catch (e) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
});
}
return {
router: t.router,
publicProcedure: t.procedure,
createProtectedProcedure: () => {
const decorated = withAuth2(t.procedure);
return decorated;
},
};
}
const t = makeTRPC<{ mything: string }>();
t.publicProcedure.query(({ ctx }) => {
expectTypeOf(ctx).toEqualTypeOf<{
mything: string;
req: any;
res: any;
}>();
});
t.createProtectedProcedure().query(({ ctx }) => {
expectTypeOf(ctx).toEqualTypeOf<{
mything: string;
auth: {
stuff: string;
};
req: any;
res: any;
}>();
});
});
});
|
5,309 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-5056-input-parser-standalone-mw-inference.test.ts | import { experimental_standaloneMiddleware, initTRPC } from '@trpc/server';
import * as z from 'zod';
describe('input/context proper narrowing in procedure chain', () => {
test("a narrower input type earlier in the chain should not widen because of a later middleware's wider input requirements", () => {
const t = initTRPC.create();
const organizationAuth = experimental_standaloneMiddleware<{
input: { organizationId?: string };
}>().create(async ({ next, ctx }) => {
return await next({ ctx });
});
t.router({
createProject: t.procedure
// input enforces that organizationId is required
.input(z.object({ organizationId: z.string().uuid() }))
// middleware allows organizationId to be optional
.use(organizationAuth)
.mutation(({ input }) => {
// input is still required
expectTypeOf(input).toEqualTypeOf<{ organizationId: string }>();
}),
updateProject: t.procedure
// input allows organizationId to be optional
.input(z.object({ organizationId: z.string().uuid().optional() }))
// middleware allows organizationId to be optional
.use(organizationAuth)
.mutation(({ input }) => {
// input remains optional
expectTypeOf(input).toEqualTypeOf<{ organizationId?: string }>();
}),
});
});
test("a narrower ctx type earlier in the chain should not widen because of a later middleware's wider ctx requirements", () => {
const t = initTRPC.context<{ organizationId: string }>().create();
const organizationCtx = experimental_standaloneMiddleware<{
ctx: { organizationId?: string };
}>().create(async ({ next }) => {
return next();
});
t.router({
createProject: t.procedure.use(organizationCtx).mutation(({ ctx }) => {
expectTypeOf(ctx).toEqualTypeOf<{ organizationId: string }>();
}),
});
});
});
|
5,310 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/issue-5075-complex-zod-serialized-inference.test.ts | import { inferRouterOutputs, initTRPC } from '@trpc/server';
import * as z from 'zod';
describe('Non-records should not erroneously be inferred as Records in serialized types', () => {
const zChange = z.object({
status: z
.tuple([
z.literal('tmp').or(z.literal('active')),
z.literal('active').or(z.literal('disabled')),
])
.optional(),
validFrom: z.tuple([z.string().nullable(), z.string()]).optional(),
validTo: z.tuple([z.string().nullable(), z.string().nullable()]).optional(),
canceled: z.tuple([z.boolean(), z.boolean()]).optional(),
startsAt: z
.tuple([z.string().nullable(), z.string().nullable()])
.optional(),
endsAt: z.tuple([z.string().nullable(), z.string().nullable()]).optional(),
});
type Change = z.infer<typeof zChange>;
test('should be inferred as object', () => {
const t = initTRPC.create();
const router = t.router({
createProject: t.procedure.output(zChange).query(() => {
return zChange.parse(null as any);
}),
createProjectNoExplicitOutput: t.procedure.query(() => {
return zChange.parse(null as any);
}),
});
type SerializedOutput = inferRouterOutputs<typeof router>['createProject'];
type SerializedOutputNoExplicitOutput = inferRouterOutputs<
typeof router
>['createProjectNoExplicitOutput'];
expectTypeOf<SerializedOutput>().toEqualTypeOf<Change>();
expectTypeOf<SerializedOutputNoExplicitOutput>().toEqualTypeOf<Change>();
});
});
describe('Zod schema serialization kitchen sink', () => {
test('Test serialization of different zod schemas against z.infer', () => {
const zObjectZArrayZRecordZTupleZUnionZIntersectionZLazyZPromiseZFunctionZMapZSetZEnumZNativeEnumZUnknownZNullableZOptionalZLiteralZBooleanZStringZNumberZBigintZDateZUndefinedZAny =
z.object({
zArray: z.array(z.string()),
zRecord: z.record(z.string()),
zTuple: z.tuple([z.string(), z.number()]),
zUnion: z.union([z.string(), z.number()]),
zIntersection: z.intersection(
z.object({ name: z.string() }),
z.object({ age: z.number() }),
),
zLazy: z.lazy(() => z.string()),
zPromise: z.promise(z.string()),
zFunction: z.function(),
zMap: z.map(z.string(), z.number()),
zSet: z.set(z.string()),
zEnum: z.enum(['foo', 'bar']),
zNativeEnum: z.nativeEnum({ foo: 1, bar: 2 }),
zUnknown: z.unknown(),
zNullable: z.nullable(z.string()),
zOptional: z.optional(z.string()),
zLiteral: z.literal('foo'),
zBoolean: z.boolean(),
zString: z.string(),
zNumber: z.number(),
zBigint: z.bigint(),
zDate: z.date(),
zUndefined: z.undefined(),
zAny: z.any(),
zArrayOptional: z.array(z.string()).optional(),
zArrayOrRecord: z.union([z.array(z.string()), z.record(z.string())]),
});
const t = initTRPC.create();
const router = t.router({
createProject: t.procedure
.output(
zObjectZArrayZRecordZTupleZUnionZIntersectionZLazyZPromiseZFunctionZMapZSetZEnumZNativeEnumZUnknownZNullableZOptionalZLiteralZBooleanZStringZNumberZBigintZDateZUndefinedZAny,
)
.query(() => {
return zObjectZArrayZRecordZTupleZUnionZIntersectionZLazyZPromiseZFunctionZMapZSetZEnumZNativeEnumZUnknownZNullableZOptionalZLiteralZBooleanZStringZNumberZBigintZDateZUndefinedZAny.parse(
null as any,
);
}),
});
type SerializedOutput = inferRouterOutputs<typeof router>['createProject'];
expectTypeOf<SerializedOutput>().toEqualTypeOf<{
zArray: string[];
zRecord: Record<string, string>;
zTuple: [string, number];
zUnion: string | number;
zIntersection: { name: string; age: number };
zLazy: string;
// eslint-disable-next-line @typescript-eslint/ban-types
zPromise: {};
// zFunction: (...args: any[]) => any; <-- not serialized, OK.
zMap: object;
zSet: object;
zEnum: 'foo' | 'bar';
zNativeEnum: number;
zUnknown?: unknown; // <-- why is this optional?
zNullable: string | null;
zOptional?: string | undefined;
zLiteral: 'foo';
zBoolean: boolean;
zString: string;
zNumber: number;
zBigint: never; // <-- should this be never or omitted?
zDate: string;
// zUndefined: undefined; <-- not serialized, OK.
zAny?: any; // <-- why is this optional?
zArrayOptional?: string[] | undefined;
zArrayOrRecord: string[] | Record<string, string>;
}>();
});
});
|
5,311 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/regression/serializable-inference.test.tsx | import { routerToServerAndClientNew } from '../___testHelpers';
import { httpLink } from '@trpc/client';
import { inferRouterOutputs, initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
import superjson from 'superjson';
describe('without transformer', () => {
const t = initTRPC.create();
const appRouter = t.router({
greeting: t.procedure.query(() => {
return {
message: 'hello',
date: new Date(),
};
}),
});
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
links: [
httpLink({
url: httpUrl,
}),
],
};
},
});
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('output', async () => {
const { proxy } = ctx;
type Output = inferRouterOutputs<typeof appRouter>['greeting'];
expectTypeOf<Output>().toEqualTypeOf<{
message: string;
date: string;
}>();
const res = await proxy.greeting.query();
expectTypeOf(res).toEqualTypeOf<{
message: string;
date: string;
}>();
});
});
describe('with transformer', () => {
const t = initTRPC.create({
transformer: superjson,
});
const appRouter = t.router({
greeting: t.procedure.query(() => {
return {
message: 'hello',
date: new Date(),
};
}),
});
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter, {
client({ httpUrl }) {
return {
transformer: superjson,
links: [
httpLink({
url: httpUrl,
}),
],
};
},
});
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('output', async () => {
const { proxy } = ctx;
type Output = inferRouterOutputs<typeof appRouter>['greeting'];
expectTypeOf<Output>().toEqualTypeOf<{
message: string;
date: Date;
}>();
const res = await proxy.greeting.query();
expectTypeOf(res).toEqualTypeOf<{
message: string;
date: Date;
}>();
});
});
|
5,312 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/showcase/dataloader.test.ts | import { routerToServerAndClientNew } from '../server/___testHelpers';
import { initTRPC } from '@trpc/server';
import { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
import DataLoader from 'dataloader';
import { konn } from 'konn';
import { z } from 'zod';
const posts = [
{
id: 1,
text: 'foo',
},
{
id: 2,
text: 'bar',
},
];
function createContext(_opts: CreateHTTPContextOptions) {
return {
postLoader: new DataLoader(async (ids: readonly number[]) => {
return ids.map((id) => posts.find((post) => post.id === id));
}),
};
}
type Context = Awaited<ReturnType<typeof createContext>>;
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.context<Context>().create();
const appRouter = t.router({
post: t.router({
byId: t.procedure
.input(
z.object({
id: z.number(),
}),
)
.query(({ input, ctx }) => ctx.postLoader.load(input.id)),
}),
});
return routerToServerAndClientNew(appRouter, {
server: {
createContext,
},
});
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('dataloader', async () => {
const result = await Promise.all([
ctx.proxy.post.byId.query({ id: 1 }),
ctx.proxy.post.byId.query({ id: 2 }),
]);
expect(result).toEqual([posts[0], posts[1]]);
});
|
5,313 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/showcase/tinyrpc.test.ts | /**
* @see https://trpc.io/blog/tinyrpc-client
*/
import '../server/___packages';
import '@trpc/server';
import { initTRPC, TRPCError } from '@trpc/server';
import { createHTTPServer } from '@trpc/server/adapters/standalone';
import fetch from 'node-fetch';
import { z } from 'zod';
import { createTinyRPCClient } from './tinyrpc';
globalThis.fetch = fetch as any;
const t = initTRPC.create({});
const router = t.router;
const publicProcedure = t.procedure;
const posts = [
{
id: '1',
title: 'Hello World',
},
];
const appRouter = router({
listPosts: publicProcedure.query(() => posts),
addPost: publicProcedure
.input(
z.object({
title: z.string(),
}),
)
.mutation((opts) => {
const id = Math.random().toString();
posts.push({
id,
title: opts.input.title,
});
return {
id,
};
}),
byId: publicProcedure
.input(
z.object({
id: z.string(),
}),
)
.query((opts) => {
const post = posts.find((p) => p.id === opts.input.id);
if (!post) throw new TRPCError({ code: 'NOT_FOUND' });
return post;
}),
});
type AppRouter = typeof appRouter;
function createServer() {
const app = createHTTPServer({
router: appRouter,
});
const { port } = app.listen(0);
return {
port: port!,
async close() {
await new Promise((resolve) => {
app.server.close(resolve);
});
},
};
}
test('tinytrpc', async () => {
const server = createServer();
const trpc = createTinyRPCClient<AppRouter>(
`http://localhost:${server.port}`,
);
const posts = await trpc.listPosts.query();
expect(posts).toMatchInlineSnapshot(`
Array [
Object {
"id": "1",
"title": "Hello World",
},
]
`);
const title = 'Hello from test';
const addedPost = await trpc.addPost.mutate({ title });
const post = await trpc.byId.query({ id: addedPost.id });
expect(post).not.toBeFalsy();
expect(post.title).toBe(title);
expect(await trpc.listPosts.query()).toHaveLength(posts.length + 1);
await server.close();
});
|
5,731 | 0 | petrpan-code/ianstormtaylor/slate/packages/slate-react | petrpan-code/ianstormtaylor/slate/packages/slate-react/test/tsconfig.json | {
"extends": "../../../config/typescript/tsconfig.json",
"references": [{ "path": "../" }]
}
|
6,842 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/check-lists.test.ts | import { test, expect } from '@playwright/test'
test.describe('Check-lists example', () => {
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/check-lists')
})
test('checks the bullet when clicked', async ({ page }) => {
const slateNodeElement = 'div[data-slate-node="element"]'
expect(await page.locator(slateNodeElement).nth(3).textContent()).toBe(
'Criss-cross!'
)
await expect(
page.locator(slateNodeElement).nth(3).locator('span').nth(1)
).toHaveCSS('text-decoration-line', 'line-through')
// Unchecking the checkboxes should un-cross the corresponding text.
await page
.locator(slateNodeElement)
.nth(3)
.locator('span')
.nth(0)
.locator('input')
.uncheck()
expect(await page.locator(slateNodeElement).nth(3).textContent()).toBe(
'Criss-cross!'
)
await expect(
page.locator(slateNodeElement).nth(3).locator('span').nth(1)
).toHaveCSS('text-decoration-line', 'none')
await expect(page.locator('p[data-slate-node="element"]')).toHaveCount(2)
})
})
|
6,843 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/code-highlighting.test.ts | import { test, expect, Page } from '@playwright/test'
test.setTimeout(60 * 1000)
test.describe('code highlighting', () => {
test.beforeEach(async ({ page }) => {
page.goto('http://localhost:3000/examples/code-highlighting')
})
for (const testCase of getTestCases()) {
const { language, content, highlights } = testCase
test(`code highlighting ${language}`, async ({ page }) => {
await setText(page, content, language)
const tokens = await page
.locator('[data-slate-editor] [data-slate-string]')
.all()
for (const [index, token] of tokens.entries()) {
const highlight = highlights[index]
const textContent = await token.textContent()
await expect(textContent).toEqual(highlight[0])
await expect(token).toHaveCSS('color', highlight[1])
}
})
}
})
// it also tests if select and code block button works the right way
async function setText(page: Page, text: string, language: string) {
await page.locator('[data-slate-editor]').fill('') // clear editor
await page.getByTestId('code-block-button').click() // convert first and the only one paragraph to code block
await page.getByTestId('language-select').selectOption({ value: language }) // select the language option
await page.keyboard.type(text) // type text
}
function getTestCases() {
const testCases: {
language: string
content: string
highlights: [string, string][]
}[] = [
{
language: 'css',
content: `body {
background-color: lightblue;
}`,
highlights: [
['body', 'rgb(102, 153, 0)'],
[' ', 'rgb(0, 0, 0)'],
['{', 'rgb(153, 153, 153)'],
[' ', 'rgb(0, 0, 0)'],
['background-color', 'rgb(153, 0, 85)'],
[':', 'rgb(153, 153, 153)'],
[' lightblue', 'rgb(0, 0, 0)'],
[';', 'rgb(153, 153, 153)'],
['}', 'rgb(153, 153, 153)'],
],
},
{
language: 'html',
content: `<body>
<h1 class="title">Testing html</h1>
</body>`,
highlights: [
['<', 'rgb(153, 0, 85)'],
['body', 'rgb(153, 0, 85)'],
['>', 'rgb(153, 0, 85)'],
[' ', 'rgb(0, 0, 0)'],
['<', 'rgb(153, 0, 85)'],
['h1', 'rgb(153, 0, 85)'],
[' ', 'rgb(153, 0, 85)'],
['class', 'rgb(102, 153, 0)'],
['=', 'rgb(0, 119, 170)'],
['"', 'rgb(0, 119, 170)'],
['title', 'rgb(0, 119, 170)'],
['"', 'rgb(0, 119, 170)'],
['>', 'rgb(153, 0, 85)'],
['Testing html', 'rgb(0, 0, 0)'],
['</', 'rgb(153, 0, 85)'],
['h1', 'rgb(153, 0, 85)'],
['>', 'rgb(153, 0, 85)'],
['</', 'rgb(153, 0, 85)'],
['body', 'rgb(153, 0, 85)'],
['>', 'rgb(153, 0, 85)'],
],
},
{
language: 'jsx',
content: `<Title title="title" renderIcon={() => <Icon />} />`,
highlights: [
['<', 'rgb(153, 0, 85)'],
['Title', 'rgb(221, 74, 104)'],
[' ', 'rgb(153, 0, 85)'],
['title', 'rgb(102, 153, 0)'],
['=', 'rgb(0, 119, 170)'],
['"', 'rgb(0, 119, 170)'],
['title', 'rgb(0, 119, 170)'],
['"', 'rgb(0, 119, 170)'],
[' ', 'rgb(153, 0, 85)'],
['renderIcon', 'rgb(102, 153, 0)'],
['=', 'rgb(153, 0, 85)'],
['{', 'rgb(153, 0, 85)'],
['(', 'rgb(153, 0, 85)'],
[')', 'rgb(153, 0, 85)'],
[' ', 'rgb(153, 0, 85)'],
['=>', 'rgb(154, 110, 58)'],
[' ', 'rgb(153, 0, 85)'],
['<', 'rgb(153, 0, 85)'],
['Icon', 'rgb(221, 74, 104)'],
[' ', 'rgb(153, 0, 85)'],
['/>', 'rgb(153, 0, 85)'],
['}', 'rgb(153, 0, 85)'],
[' ', 'rgb(153, 0, 85)'],
['/>', 'rgb(153, 0, 85)'],
],
},
]
return testCases
}
|
6,844 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/editable-voids.test.ts | import { test, expect } from '@playwright/test'
test.describe('editable voids', () => {
const input = 'input[type="text"]'
const elements = [
{ tag: 'h4', count: 3 },
{ tag: input, count: 1 },
{ tag: 'input[type="radio"]', count: 2 },
]
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/editable-voids')
})
test('checks for the elements', async ({ page }) => {
for (const elem of elements) {
const { tag, count } = elem
await expect(page.locator(tag)).toHaveCount(count)
}
})
test('should double the elements', async ({ page }) => {
// click the `+` sign to duplicate the editable void
await page.locator('span.material-icons').nth(1).click()
for (const elem of elements) {
const { tag, count } = elem
await expect(page.locator(tag)).toHaveCount(count * 2)
}
})
test('make sure you can edit editable void', async ({ page }) => {
await page.locator(input).fill('Typing')
expect(await page.locator(input).inputValue()).toBe('Typing')
})
})
|
6,845 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/embeds.test.ts | import { test, expect } from '@playwright/test'
test.describe('embeds example', () => {
const slateEditor = 'div[data-slate-editor="true"]'
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/embeds')
})
test('contains embeded', async ({ page }) => {
await expect(page.locator(slateEditor).locator('iframe')).toHaveCount(1)
})
})
|
6,846 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/forced-layout.test.ts | import { test, expect } from '@playwright/test'
test.describe('forced layout example', () => {
const elements = [
{ tag: '#__next h2', count: 1 },
{ tag: '#__next p', count: 1 },
]
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/forced-layout')
})
test('checks for the elements', async ({ page }) => {
for (const { tag, count } of elements) {
await expect(page.locator(tag)).toHaveCount(count)
}
})
test('checks if elements persist even after everything is deleted', async ({
page,
}) => {
// clear the textbox
await page.locator('div[role="textbox"]').clear()
for (const { tag, count } of elements) {
await expect(page.locator(tag)).toHaveCount(count)
}
})
})
|
6,847 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/hovering-toolbar.test.ts | import { test, expect } from '@playwright/test'
test.describe('hovering toolbar example', () => {
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/hovering-toolbar')
})
test('hovering toolbar appears', async ({ page }) => {
await page.pause()
await expect(page.getByTestId('menu')).toHaveCSS('opacity', '0')
await page.locator('span[data-slate-string="true"]').nth(0).selectText()
await expect(page.getByTestId('menu')).toHaveCount(1)
await expect(page.getByTestId('menu')).toHaveCSS('opacity', '1')
await expect(
page.getByTestId('menu').locator('span.material-icons')
).toHaveCount(3)
})
test('hovering toolbar disappears', async ({ page }) => {
await page.locator('span[data-slate-string="true"]').nth(0).selectText()
await expect(page.getByTestId('menu')).toHaveCSS('opacity', '1')
await page.locator('span[data-slate-string="true"]').nth(0).selectText()
await page
.locator('div')
.nth(0)
.click({ force: true, position: { x: 0, y: 0 } })
await expect(page.getByTestId('menu')).toHaveCSS('opacity', '0')
})
})
|
6,848 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/huge-document.test.ts | import { test, expect } from '@playwright/test'
test.describe('huge document example', () => {
const elements = [
{ tag: '#__next h1', count: 100 },
{ tag: '#__next p', count: 700 },
]
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/huge-document')
})
test('contains image', async ({ page }) => {
for (const { tag, count } of elements) {
await expect(page.locator(tag)).toHaveCount(count)
}
})
})
|
6,849 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/iframe.test.ts | import { test, expect, Page } from '@playwright/test'
test.describe('iframe editor', () => {
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/iframe')
})
test('should be editable', async ({ page }) => {
await page
.frameLocator('iframe')
.locator('body')
.getByRole('textbox')
.focus()
await page.keyboard.press('Home')
await page.keyboard.type('Hello World')
expect(
await page
.frameLocator('iframe')
.locator('body')
.getByRole('textbox')
.textContent()
).toContain('Hello World')
})
})
|
6,850 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/images.test.ts | import { test, expect } from '@playwright/test'
test.describe('images example', () => {
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/images')
})
test('contains image', async ({ page }) => {
await expect(page.getByRole('textbox').locator('img')).toHaveCount(2)
})
})
|
6,851 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/inlines.test.ts | import { test, expect } from '@playwright/test'
test.describe('Inlines example', () => {
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/inlines')
})
test('contains link', async ({ page }) => {
expect(
await page.getByRole('textbox').locator('a').nth(0).innerText()
).toContain('hyperlink')
})
// FIXME: unstable, has issues with selection.anchorNode
test.skip('arrow keys skip over read-only inline', async ({ page }) => {
const badge = page.locator('text=Approved >> xpath=../../..')
// Put cursor after the badge
await badge.evaluate(badgeElement => {
const range = document.createRange()
range.setStartAfter(badgeElement)
range.setEndAfter(badgeElement)
const selection = window.getSelection()!
selection.removeAllRanges()
selection.addRange(range)
})
const getSelectionContainerText = () =>
page.evaluate(() => {
const selection = window.getSelection()!
return selection.anchorNode!.textContent
})
expect(await getSelectionContainerText()).toBe('.')
await page.keyboard.press('ArrowLeft')
expect(await getSelectionContainerText()).toBe(
'! Here is a read-only inline: '
)
await page.keyboard.press('ArrowRight')
expect(await getSelectionContainerText()).toBe('.')
})
})
|
6,852 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/markdown-preview.test.ts | import { test, expect } from '@playwright/test'
test.describe('markdown preview', () => {
const slateEditor = 'div[data-slate-editor="true"]'
const markdown = 'span[data-slate-string="true"]'
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/markdown-preview')
})
test('checks for markdown', async ({ page }) => {
await expect(page.locator(slateEditor).locator(markdown)).toHaveCount(9)
await page.locator(slateEditor).click()
await page.keyboard.press('End')
await page.keyboard.press('Enter')
await page.keyboard.type('## Try it out!')
await page.keyboard.press('Enter')
await page.pause()
await expect(page.locator(slateEditor).locator(markdown)).toHaveCount(10)
})
})
|
6,853 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/markdown-shortcuts.test.ts | import { test, expect } from '@playwright/test'
test.describe('On markdown-shortcuts example', () => {
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/markdown-shortcuts')
})
test('contains quote', async ({ page }) => {
expect(
await page.getByRole('textbox').locator('blockquote').textContent()
).toContain('A wise quote.')
})
test('can add list items', async ({ page }, testInfo) => {
await expect(page.getByRole('textbox').locator('ul')).toHaveCount(0)
await page.getByRole('textbox').click()
await page
.getByRole('textbox')
.press(testInfo.project.name === 'webkit' ? 'Meta+ArrowLeft' : 'Home')
await page.getByRole('textbox').pressSequentially('* ')
await page.getByRole('textbox').pressSequentially('1st Item')
await page.keyboard.press('Enter')
await page.getByRole('textbox').pressSequentially('2nd Item')
await page.keyboard.press('Enter')
await page.getByRole('textbox').pressSequentially('3rd Item')
await page.keyboard.press('Enter')
await page.keyboard.press('Backspace')
await expect(page.locator('ul > li')).toHaveCount(3)
expect(await page.locator('ul > li').nth(0).innerText()).toContain(
'1st Item'
)
expect(await page.locator('ul > li').nth(1).innerText()).toContain(
'2nd Item'
)
expect(await page.locator('ul > li').nth(2).innerText()).toContain(
'3rd Item'
)
})
test('can add a h1 item', async ({ page }) => {
await expect(page.getByRole('textbox').locator('h1')).toHaveCount(0)
await page.getByRole('textbox').press('Enter')
await page.getByRole('textbox').press('ArrowLeft')
await page.getByRole('textbox').pressSequentially('# ')
await page.getByRole('textbox').pressSequentially('Heading')
await expect(page.locator('h1')).toHaveCount(1)
expect(
await page.getByRole('textbox').locator('h1').textContent()
).toContain('Heading')
})
})
|
6,854 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/mentions.test.ts | import { test, expect } from '@playwright/test'
test.describe('mentions example', () => {
test.beforeEach(
async ({ page }) =>
await page.goto('http://localhost:3000/examples/mentions')
)
test('renders mention element', async ({ page }) => {
await expect(page.locator('[data-cy="mention-R2-D2"]')).toHaveCount(1)
await expect(page.locator('[data-cy="mention-Mace-Windu"]')).toHaveCount(1)
})
test('shows list of mentions', async ({ page }) => {
await page.getByRole('textbox').click()
await page.getByRole('textbox').selectText()
await page.getByRole('textbox').press('Backspace')
await page.getByRole('textbox').pressSequentially(' @ma')
await expect(page.locator('[data-cy="mentions-portal"]')).toHaveCount(1)
})
test('inserts on enter from list', async ({ page }) => {
await page.getByRole('textbox').click()
await page.getByRole('textbox').selectText()
await page.getByRole('textbox').press('Backspace')
await page.getByRole('textbox').pressSequentially(' @Ja')
await page.getByRole('textbox').press('Enter')
await expect(page.locator('[data-cy="mention-Jabba"]')).toHaveCount(1)
})
})
|
6,855 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/paste-html.test.ts | import { test, expect, Page } from '@playwright/test'
test.describe('paste html example', () => {
test.beforeEach(
async ({ page }) =>
await page.goto('http://localhost:3000/examples/paste-html')
)
const pasteHtml = async (page: Page, htmlContent: string) => {
await page.getByRole('textbox').click()
await page.getByRole('textbox').selectText()
await page.keyboard.press('Backspace')
await page
.getByRole('textbox')
.evaluate((el: HTMLElement, htmlContent: string) => {
const clipboardEvent = Object.assign(
new Event('paste', { bubbles: true, cancelable: true }),
{
clipboardData: {
getData: (type = 'text/html') => htmlContent,
types: ['text/html'],
},
}
)
el.dispatchEvent(clipboardEvent)
}, htmlContent)
}
test('pasted bold text uses <strong>', async ({ page }) => {
await pasteHtml(page, '<strong>Hello Bold</strong>')
expect(await page.locator('strong').textContent()).toContain('Hello')
})
test('pasted code uses <code>', async ({ page }) => {
await pasteHtml(page, '<code>console.log("hello from slate!")</code>')
expect(await page.locator('code').textContent()).toContain('slate!')
})
})
|
6,856 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/placeholder.test.ts | import { test, expect } from '@playwright/test'
test.describe('placeholder example', () => {
test.beforeEach(
async ({ page }) =>
await page.goto('http://localhost:3000/examples/custom-placeholder')
)
test('renders custom placeholder', async ({ page }) => {
const placeholderElement = page.locator('[data-slate-placeholder=true]')
expect(await placeholderElement.textContent()).toContain('Type something')
expect(await page.locator('pre').textContent()).toContain(
'renderPlaceholder'
)
})
test('renders editor tall enough to fit placeholder', async ({ page }) => {
const slateEditor = page.locator('[data-slate-editor=true]')
const placeholderElement = page.locator('[data-slate-placeholder=true]')
await expect(placeholderElement).toBeVisible()
const editorBoundingBox = await slateEditor.boundingBox()
const placeholderBoundingBox = await placeholderElement.boundingBox()
if (!editorBoundingBox)
throw new Error('Could not get bounding box for editor')
if (!placeholderBoundingBox)
throw new Error('Could not get bounding box for placeholder')
expect(editorBoundingBox.height).toBeGreaterThanOrEqual(
placeholderBoundingBox.height
)
})
})
|
6,857 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/plaintext.test.ts | import { test, expect } from '@playwright/test'
test.describe('plaintext example', () => {
test.beforeEach(
async ({ page }) =>
await page.goto('http://localhost:3000/examples/plaintext')
)
test('inserts text when typed', async ({ page }) => {
await page.getByRole('textbox').press('Home')
await page.getByRole('textbox').pressSequentially('Hello World')
expect(await page.getByRole('textbox').textContent()).toContain(
'Hello World'
)
})
})
|
6,858 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/read-only.test.ts | import { test, expect } from '@playwright/test'
test.describe('readonly editor', () => {
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/read-only')
})
test('should not be editable', async ({ page }) => {
const slateEditor = '[data-slate-editor="true"]'
expect(
await page.locator(slateEditor).getAttribute('contentEditable')
).toBe('false')
expect(await page.locator(slateEditor).getAttribute('role')).toBe(null)
await page.locator(slateEditor).click()
await expect(page.locator(slateEditor)).not.toBeFocused()
})
})
|
6,859 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/richtext.test.ts | import { test, expect } from '@playwright/test'
test.describe('On richtext example', () => {
test.beforeEach(
async ({ page }) =>
await page.goto('http://localhost:3000/examples/richtext')
)
test('renders rich text', async ({ page }) => {
expect(await page.locator('strong').nth(0).textContent()).toContain('rich')
expect(await page.locator('blockquote').textContent()).toContain(
'wise quote'
)
})
test('inserts text when typed', async ({ page }) => {
await page.getByRole('textbox').press('Home')
await page.getByRole('textbox').pressSequentially('Hello World')
expect(await page.getByRole('textbox').textContent()).toContain(
'Hello World'
)
})
})
|
6,860 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/search-highlighting.test.ts | import { test, expect } from '@playwright/test'
test.describe('search highlighting', () => {
test.beforeEach(
async ({ page }) =>
await page.goto('http://localhost:3000/examples/search-highlighting')
)
test('highlights the searched text', async ({ page }) => {
const searchField = 'input[type="search"]'
const highlightedText = 'search-highlighted'
await page.locator(searchField).fill('text')
await expect(page.locator(`[data-cy="${highlightedText}"]`)).toHaveCount(2)
})
})
|
6,861 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/select.test.ts | import { test, expect } from '@playwright/test'
test.describe('selection', () => {
const slateEditor = '[data-slate-node="element"]'
test.beforeEach(
async ({ page }) =>
await page.goto('http://localhost:3000/examples/richtext')
)
test('select the correct block when triple clicking', async ({ page }) => {
// triple clicking the second block (paragraph) shouldn't highlight the
// quote button
for (let i = 0; i < 3; i++) {
await page.locator(slateEditor).nth(1).click()
}
await page.pause()
// .css-1vdn1ty is the gray, unselected button
expect(await page.locator('.css-1vdn1ty').nth(6).textContent()).toBe(
'format_quote'
)
})
})
|
6,862 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/shadow-dom.test.ts | import { test, expect } from '@playwright/test'
test.describe('shadow-dom example', () => {
test.beforeEach(
async ({ page }) =>
await page.goto('http://localhost:3000/examples/shadow-dom')
)
test('renders slate editor inside nested shadow', async ({ page }) => {
const outerShadow = page.locator('[data-cy="outer-shadow-root"]')
const innerShadow = outerShadow.locator('> div')
await expect(innerShadow.getByRole('textbox')).toHaveCount(1)
})
})
|
6,863 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/styling.test.ts | import { test, expect } from '@playwright/test'
test.describe('styling example', () => {
test.beforeEach(
async ({ page }) =>
await page.goto('http://localhost:3000/examples/styling')
)
test('applies styles to editor from style prop', async ({ page }) => {
page.waitForLoadState('domcontentloaded')
const editor = page.locator('[data-slate-editor=true]').nth(0)
const styles = await editor.evaluate(el => {
const {
backgroundColor,
minHeight,
outlineWidth,
outlineStyle,
outlineColor,
position,
whiteSpace,
wordWrap,
} = window.getComputedStyle(el)
return {
backgroundColor,
minHeight,
outlineWidth,
outlineStyle,
outlineColor,
position,
whiteSpace,
wordWrap,
}
})
// Provided styles
expect(styles.backgroundColor).toBe('rgb(255, 230, 156)')
expect(styles.minHeight).toBe('200px')
expect(styles.outlineWidth).toBe('2px')
expect(styles.outlineStyle).toBe('solid')
expect(styles.outlineColor).toBe('rgb(0, 128, 0)')
// Default styles
expect(styles.position).toBe('relative')
expect(styles.whiteSpace).toBe('pre-wrap')
expect(styles.wordWrap).toBe('break-word')
})
test('applies styles to editor from className prop', async ({ page }) => {
page.waitForLoadState('domcontentloaded')
const editor = page.locator('[data-slate-editor=true]').nth(1)
const styles = await editor.evaluate(el => {
const {
backgroundColor,
paddingTop,
paddingRight,
paddingBottom,
paddingLeft,
fontSize,
minHeight,
outlineWidth,
outlineStyle,
outlineColor,
borderTopLeftRadius,
borderTopRightRadius,
borderBottomRightRadius,
borderBottomLeftRadius,
outlineOffset,
position,
whiteSpace,
wordWrap,
} = window.getComputedStyle(el)
return {
backgroundColor,
paddingTop,
paddingRight,
paddingBottom,
paddingLeft,
fontSize,
minHeight,
outlineWidth,
outlineStyle,
outlineColor,
borderTopLeftRadius,
borderTopRightRadius,
borderBottomRightRadius,
borderBottomLeftRadius,
outlineOffset,
position,
whiteSpace,
wordWrap,
}
})
expect(styles.backgroundColor).toBe('rgb(218, 225, 255)')
expect(styles.paddingTop).toBe('40px')
expect(styles.paddingRight).toBe('40px')
expect(styles.paddingBottom).toBe('40px')
expect(styles.paddingLeft).toBe('40px')
expect(styles.fontSize).toBe('20px')
expect(styles.minHeight).toBe('150px')
expect(styles.borderBottomLeftRadius).toBe('20px')
expect(styles.borderBottomRightRadius).toBe('20px')
expect(styles.borderTopLeftRadius).toBe('20px')
expect(styles.borderTopRightRadius).toBe('20px')
expect(styles.outlineOffset).toBe('-20px')
expect(styles.outlineWidth).toBe('3px')
expect(styles.outlineStyle).toBe('dashed')
expect(styles.outlineColor).toBe('rgb(0, 94, 128)')
expect(styles.whiteSpace).toBe('pre-wrap')
})
})
|
6,864 | 0 | petrpan-code/ianstormtaylor/slate/playwright/integration | petrpan-code/ianstormtaylor/slate/playwright/integration/examples/tables.test.ts | import { test, expect } from '@playwright/test'
test.describe('table example', () => {
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000/examples/tables')
})
test('table tag rendered', async ({ page }) => {
await expect(page.getByRole('textbox').locator('table')).toHaveCount(1)
})
})
|
7,111 | 0 | petrpan-code/mattermost/mattermost/e2e-tests/cypress/tests/integration/channels | petrpan-code/mattermost/mattermost/e2e-tests/cypress/tests/integration/channels/autocomplete/common_test.ts | // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
// ***************************************************************
// - [#] indicates a test step (e.g. # Go to a page)
// - [*] indicates an assertion (e.g. * Check the title)
// - Use element ID when selecting an element. Create one if none.
// ***************************************************************
import {
getPostTextboxInput,
getQuickChannelSwitcherInput,
SimpleUser,
startAtMention,
verifySuggestionAtChannelSwitcher,
verifySuggestionAtPostTextbox,
} from './helpers';
export function doTestPostextbox(mention: string, ...suggestion: Cypress.UserProfile[]) {
getPostTextboxInput();
startAtMention(mention);
verifySuggestionAtPostTextbox(...suggestion);
}
export function doTestQuickChannelSwitcher(mention: string, ...suggestion: Cypress.UserProfile[]) {
getQuickChannelSwitcherInput();
startAtMention(mention);
verifySuggestionAtChannelSwitcher(...suggestion);
}
export function doTestUserChannelSection(prefix: string, testTeam: Cypress.Team, testUsers: Record<string, SimpleUser>) {
const thor = testUsers.thor;
const loki = testUsers.loki;
// # Create new channel and add user to channel
const channelName = 'new-channel';
cy.apiCreateChannel(testTeam.id, channelName, channelName).then(({channel}) => {
cy.apiGetUserByEmail(thor.email).then(({user}) => {
cy.apiAddUserToChannel(channel.id, user.id);
});
cy.visit(`/${testTeam.name}/channels/${channel.name}`);
});
// # Start an at mention that should return 2 users (in this case, the users share a last name)
cy.uiGetPostTextBox().
as('input').
clear().
type(`@${prefix}odinson`);
// * Thor should be a channel member
cy.uiVerifyAtMentionInSuggestionList(thor as Cypress.UserProfile, true);
// * Loki should NOT be a channel member
cy.uiVerifyAtMentionInSuggestionList(loki as Cypress.UserProfile, false);
}
export function doTestDMChannelSidebar(testUsers: Record<string, SimpleUser>) {
const thor = testUsers.thor;
// # Open of the add direct message modal
cy.uiAddDirectMessage().click({force: true});
// # Type username into input
cy.get('.more-direct-channels').
find('input').
should('exist').
type(thor.username, {force: true});
cy.intercept({
method: 'POST',
url: '/api/v4/users/search',
}).as('searchUsers');
cy.wait('@searchUsers').then((interception) => {
expect(interception.response.body.length === 1);
});
// * There should only be one result
cy.get('#moreDmModal').find('.more-modal__row').
as('result').
its('length').
should('equal', 1);
// * Result should have appropriate text
cy.get('@result').
find('.more-modal__name').
should('have.text', `@${thor.username} - ${thor.first_name} ${thor.last_name} (${thor.nickname})`);
cy.get('@result').
find('.more-modal__description').
should('have.text', thor.email);
// # Click on the result to add user
cy.get('@result').click({force: true});
// # Click "Go"
cy.uiGetButton('Go').click();
// # Should land on direct message channel for that user
cy.get('#channelHeaderTitle').should('have.text', thor.username + ' ');
}
|
1,879 | 0 | petrpan-code/nrwl/nx/e2e/angular-core | petrpan-code/nrwl/nx/e2e/angular-core/src/config.test.ts | import {
checkFilesExist,
cleanupProject,
newProject,
removeFile,
runCLI,
uniq,
updateFile,
} from '@nx/e2e/utils';
describe('angular.json v1 config', () => {
const app1 = uniq('app1');
beforeAll(() => {
newProject();
runCLI(
`generate @nx/angular:app ${app1} --project-name-and-root-format=as-provided --no-interactive`
);
// reset workspace to use v1 config
updateFile(`angular.json`, angularV1Json(app1));
removeFile(`${app1}/project.json`);
removeFile(`${app1}-e2e/project.json`);
});
afterAll(() => cleanupProject());
it('should support projects in angular.json v1 config', async () => {
expect(runCLI(`build ${app1}`)).toContain('Successfully ran target build');
expect(runCLI(`test ${app1} --no-watch`)).toContain(
'Successfully ran target test'
);
}, 1000000);
it('should generate new app with project.json and keep the existing in angular.json', async () => {
// create new app
const app2 = uniq('app2');
runCLI(
`generate @nx/angular:app ${app2} --project-name-and-root-format=as-provided --no-interactive`
);
// should generate project.json for new projects
checkFilesExist(`${app2}/project.json`);
// check it works correctly
expect(runCLI(`build ${app2}`)).toContain('Successfully ran target build');
expect(runCLI(`test ${app2} --no-watch`)).toContain(
'Successfully ran target test'
);
// check existing app in angular.json still works
expect(runCLI(`build ${app1}`)).toContain('Successfully ran target build');
expect(runCLI(`test ${app1} --no-watch`)).toContain(
'Successfully ran target test'
);
}, 1000000);
});
const angularV1Json = (appName: string) => `{
"version": 1,
"projects": {
"${appName}": {
"projectType": "application",
"root": "${appName}",
"sourceRoot": "${appName}/src",
"prefix": "v1angular",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist${appName}",
"index": "${appName}/src/index.html",
"main": "${appName}/src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "${appName}/tsconfig.app.json",
"assets": ["${appName}/src/favicon.ico", "${appName}/src/assets"],
"styles": ["${appName}/src/styles.css"],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "${appName}:build:production"
},
"development": {
"browserTarget": "${appName}:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "${appName}:build"
}
},
"lint": {
"builder": "@nx/eslint:lint",
"options": {
"lintFilePatterns": [
"${appName}/src/**/*.ts",
"${appName}/src/**/*.html"
]
}
},
"test": {
"builder": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage${appName}"],
"options": {
"jestConfig": "${appName}/jest.config.ts",
"passWithNoTests": true
}
}
},
"tags": []
},
"${appName}-e2e": {
"root": "${appName}-e2e",
"sourceRoot": "${appName}-e2e/src",
"projectType": "application",
"architect": {
"e2e": {
"builder": "@nx/cypress:cypress",
"options": {
"cypressConfig": "${appName}-e2e/cypress.json",
"devServerTarget": "${appName}:serve:development",
"testingType": "e2e"
},
"configurations": {
"production": {
"devServerTarget": "${appName}:serve:production"
}
}
},
"lint": {
"builder": "@nx/eslint:lint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": ["${appName}-e2e/**/*.{js,ts}"]
}
}
},
"tags": [],
"implicitDependencies": ["${appName}"]
}
}
}
`;
|
1,880 | 0 | petrpan-code/nrwl/nx/e2e/angular-core | petrpan-code/nrwl/nx/e2e/angular-core/src/module-federation.test.ts | import { names } from '@nx/devkit';
import {
checkFilesExist,
cleanupProject,
killProcessAndPorts,
newProject,
readJson,
runCLI,
runCommandUntil,
runE2ETests,
uniq,
updateFile,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('Angular Module Federation', () => {
let proj: string;
let oldVerboseLoggingValue: string;
beforeAll(() => {
proj = newProject();
oldVerboseLoggingValue = process.env.NX_E2E_VERBOSE_LOGGING;
process.env.NX_E2E_VERBOSE_LOGGING = 'true';
});
afterAll(() => {
cleanupProject();
process.env.NX_E2E_VERBOSE_LOGGING = oldVerboseLoggingValue;
});
it('should generate valid host and remote apps', async () => {
const hostApp = uniq('app');
const remoteApp1 = uniq('remote');
const sharedLib = uniq('shared-lib');
const secondaryEntry = uniq('secondary');
const hostPort = 4300;
const remotePort = 4301;
// generate host app
runCLI(
`generate @nx/angular:host ${hostApp} --style=css --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
// generate remote app
runCLI(
`generate @nx/angular:remote ${remoteApp1} --host=${hostApp} --port=${remotePort} --style=css --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
// check files are generated without the layout directory ("apps/")
checkFilesExist(
`${hostApp}/src/app/app.module.ts`,
`${remoteApp1}/src/app/app.module.ts`
);
// check default generated host is built successfully
const buildOutput = runCLI(`build ${hostApp}`);
expect(buildOutput).toContain('Successfully ran target build');
// generate a shared lib with a seconary entry point
runCLI(
`generate @nx/angular:library ${sharedLib} --buildable --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/angular:library-secondary-entry-point --library=${sharedLib} --name=${secondaryEntry} --no-interactive`
);
// update host & remote files to use shared library
updateFile(
`${hostApp}/src/app/app.module.ts`,
`import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ${
names(sharedLib).className
}Module } from '@${proj}/${sharedLib}';
import { ${
names(secondaryEntry).className
}Module } from '@${proj}/${sharedLib}/${secondaryEntry}';
import { AppComponent } from './app.component';
import { NxWelcomeComponent } from './nx-welcome.component';
import { RouterModule } from '@angular/router';
@NgModule({
declarations: [AppComponent, NxWelcomeComponent],
imports: [
BrowserModule,
${names(sharedLib).className}Module,
RouterModule.forRoot(
[
{
path: '${remoteApp1}',
loadChildren: () =>
import('${remoteApp1}/Module').then(
(m) => m.RemoteEntryModule
),
},
],
{ initialNavigation: 'enabledBlocking' }
),
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
`
);
updateFile(
`${remoteApp1}/src/app/remote-entry/entry.module.ts`,
`import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { ${names(sharedLib).className}Module } from '@${proj}/${sharedLib}';
import { ${
names(secondaryEntry).className
}Module } from '@${proj}/${sharedLib}/${secondaryEntry}';
import { RemoteEntryComponent } from './entry.component';
import { NxWelcomeComponent } from './nx-welcome.component';
@NgModule({
declarations: [RemoteEntryComponent, NxWelcomeComponent],
imports: [
CommonModule,
${names(sharedLib).className}Module,
RouterModule.forChild([
{
path: '',
component: RemoteEntryComponent,
},
]),
],
providers: [],
})
export class RemoteEntryModule {}
`
);
const processSwc = await runCommandUntil(
`serve ${hostApp} --port=${hostPort} --dev-remotes=${remoteApp1}`,
(output) =>
!output.includes(`Remote '${remoteApp1}' failed to serve correctly`) &&
output.includes(`listening on localhost:${hostPort}`)
);
await killProcessAndPorts(processSwc.pid, hostPort, remotePort);
const processTsNode = await runCommandUntil(
`serve ${hostApp} --port=${hostPort} --dev-remotes=${remoteApp1}`,
(output) =>
!output.includes(`Remote '${remoteApp1}' failed to serve correctly`) &&
output.includes(`listening on localhost:${hostPort}`),
{ env: { NX_PREFER_TS_NODE: 'true' } }
);
await killProcessAndPorts(processTsNode.pid, hostPort, remotePort);
}, 20_000_000);
it('should convert apps to MF successfully', async () => {
const app1 = uniq('app1');
const app2 = uniq('app2');
const app1Port = 4400;
const app2Port = 4401;
// generate apps
runCLI(
`generate @nx/angular:application ${app1} --routing --bundler=webpack --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/angular:application ${app2} --bundler=webpack --project-name-and-root-format=as-provided --no-interactive`
);
// convert apps
runCLI(
`generate @nx/angular:setup-mf ${app1} --mfType=host --port=${app1Port} --no-interactive`
);
runCLI(
`generate @nx/angular:setup-mf ${app2} --mfType=remote --host=${app1} --port=${app2Port} --no-interactive`
);
const processSwc = await runCommandUntil(
`serve ${app1} --dev-remotes=${app2}`,
(output) =>
!output.includes(`Remote '${app2}' failed to serve correctly`) &&
output.includes(`listening on localhost:${app1Port}`)
);
await killProcessAndPorts(processSwc.pid, app1Port, app2Port);
const processTsNode = await runCommandUntil(
`serve ${app1} --dev-remotes=${app2}`,
(output) =>
!output.includes(`Remote '${app2}' failed to serve correctly`) &&
output.includes(`listening on localhost:${app1Port}`),
{ env: { NX_PREFER_TS_NODE: 'true' } }
);
await killProcessAndPorts(processTsNode.pid, app1Port, app2Port);
}, 20_000_000);
it('should scaffold MF + SSR setup successfully', async () => {
const host = uniq('host');
const remote1 = uniq('remote1');
const remote2 = uniq('remote2');
// generate remote apps
runCLI(
`generate @nx/angular:host ${host} --ssr --remotes=${remote1},${remote2} --project-name-and-root-format=as-provided --no-interactive`
);
// ports
const hostPort = 4500;
const remote1Port = readJson(join(remote1, 'project.json')).targets.serve
.options.port;
const remote2Port = readJson(join(remote2, 'project.json')).targets.serve
.options.port;
const processSwc = await runCommandUntil(
`serve-ssr ${host} --port=${hostPort}`,
(output) =>
output.includes(
`Node Express server listening on http://localhost:${remote1Port}`
) &&
output.includes(
`Node Express server listening on http://localhost:${remote2Port}`
) &&
output.includes(
`Angular Universal Live Development Server is listening`
)
);
await killProcessAndPorts(
processSwc.pid,
hostPort,
remote1Port,
remote2Port
);
const processTsNode = await runCommandUntil(
`serve-ssr ${host} --port=${hostPort}`,
(output) =>
output.includes(
`Node Express server listening on http://localhost:${remote1Port}`
) &&
output.includes(
`Node Express server listening on http://localhost:${remote2Port}`
) &&
output.includes(
`Angular Universal Live Development Server is listening`
),
{ env: { NX_PREFER_TS_NODE: 'true' } }
);
await killProcessAndPorts(
processTsNode.pid,
hostPort,
remote1Port,
remote2Port
);
}, 20_000_000);
it('should should support generating host and remote apps with --project-name-and-root-format=derived', async () => {
const hostApp = uniq('host');
const remoteApp = uniq('remote');
const hostPort = 4800;
const remotePort = 4801;
// generate host app
runCLI(
`generate @nx/angular:host ${hostApp} --no-standalone --project-name-and-root-format=derived --no-interactive`
);
// generate remote app
runCLI(
`generate @nx/angular:remote ${remoteApp} --host=${hostApp} --port=${remotePort} --no-standalone --project-name-and-root-format=derived --no-interactive`
);
// check files are generated with the layout directory ("apps/")
checkFilesExist(
`apps/${hostApp}/src/app/app.module.ts`,
`apps/${remoteApp}/src/app/app.module.ts`
);
// check default generated host is built successfully
const buildOutputSwc = await runCommandUntil(`build ${hostApp}`, (output) =>
output.includes('Successfully ran target build')
);
await killProcessAndPorts(buildOutputSwc.pid);
const buildOutputTsNode = await runCommandUntil(
`build ${hostApp}`,
(output) => output.includes('Successfully ran target build'),
{
env: { NX_PREFER_TS_NODE: 'true' },
}
);
await killProcessAndPorts(buildOutputTsNode.pid);
const processSwc = await runCommandUntil(
`serve ${hostApp} --port=${hostPort} --dev-remotes=${remoteApp}`,
(output) =>
!output.includes(`Remote '${remoteApp}' failed to serve correctly`) &&
output.includes(`listening on localhost:${hostPort}`)
);
await killProcessAndPorts(processSwc.pid, hostPort, remotePort);
const processTsNode = await runCommandUntil(
`serve ${hostApp} --port=${hostPort} --dev-remotes=${remoteApp}`,
(output) =>
!output.includes(`Remote '${remoteApp}' failed to serve correctly`) &&
output.includes(`listening on localhost:${hostPort}`),
{
env: { NX_PREFER_TS_NODE: 'true' },
}
);
await killProcessAndPorts(processTsNode.pid, hostPort, remotePort);
}, 20_000_000);
it('should federate a module from a library and update an existing remote', async () => {
const lib = uniq('lib');
const remote = uniq('remote');
const module = uniq('module');
const host = uniq('host');
const hostPort = 4200;
runCLI(
`generate @nx/angular:host ${host} --remotes=${remote} --no-interactive --projectNameAndRootFormat=as-provided`
);
runCLI(
`generate @nx/js:lib ${lib} --no-interactive --projectNameAndRootFormat=as-provided`
);
// Federate Module
runCLI(
`generate @nx/angular:federate-module ${lib}/src/index.ts --name=${module} --remote=${remote} --no-interactive`
);
updateFile(`${lib}/src/index.ts`, `export { isEven } from './lib/${lib}';`);
updateFile(
`${lib}/src/lib/${lib}.ts`,
`export function isEven(num: number) { return num % 2 === 0; }`
);
// Update Host to use the module
updateFile(
`${host}/src/app/app.component.ts`,
`
import { Component } from '@angular/core';
import { isEven } from '${remote}/${module}';
@Component({
selector: 'proj-root',
template: \`<div class="host">{{title}}</div>\`,
standalone: true
})
export class AppComponent {
title = \`shell is \${isEven(2) ? 'even' : 'odd'}\`;
}`
);
// Update e2e test to check the module
updateFile(
`${host}-e2e/src/e2e/app.cy.ts`,
`
describe('${host}', () => {
beforeEach(() => cy.visit('/'));
it('should display contain the remote library', () => {
expect(cy.get('div.host')).to.exist;
expect(cy.get('div.host').contains('shell is even'));
});
});
`
);
// Build host and remote
const buildOutput = await runCommandUntil(`build ${host}`, (output) =>
output.includes('Successfully ran target build')
);
await killProcessAndPorts(buildOutput.pid);
const remoteOutput = await runCommandUntil(`build ${remote}`, (output) =>
output.includes('Successfully ran target build')
);
await killProcessAndPorts(remoteOutput.pid);
if (runE2ETests()) {
const hostE2eResults = await runCommandUntil(
`e2e ${host}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);
await killProcessAndPorts(hostE2eResults.pid, hostPort, hostPort + 1);
}
}, 500_000);
it('should federate a module from a library and create a remote that is served recursively', async () => {
const lib = uniq('lib');
const remote = uniq('remote');
const childRemote = uniq('childremote');
const module = uniq('module');
const host = uniq('host');
const hostPort = 4200;
runCLI(
`generate @nx/angular:host ${host} --remotes=${remote} --no-interactive --projectNameAndRootFormat=as-provided`
);
runCLI(
`generate @nx/js:lib ${lib} --no-interactive --projectNameAndRootFormat=as-provided`
);
// Federate Module
runCLI(
`generate @nx/angular:federate-module ${lib}/src/index.ts --name=${module} --remote=${childRemote} --no-interactive`
);
updateFile(`${lib}/src/index.ts`, `export { isEven } from './lib/${lib}';`);
updateFile(
`${lib}/src/lib/${lib}.ts`,
`export function isEven(num: number) { return num % 2 === 0; }`
);
// Update Host to use the module
updateFile(
`${remote}/src/app/remote-entry/entry.component.ts`,
`
import { Component } from '@angular/core';
import { isEven } from '${childRemote}/${module}';
@Component({
selector: 'proj-${remote}-entry',
template: \`<div class="childremote">{{title}}</div>\`,
standalone: true
})
export class RemoteEntryComponent {
title = \`shell is \${isEven(2) ? 'even' : 'odd'}\`;
}`
);
updateFile(
`${remote}/module-federation.config.ts`,
`
import { ModuleFederationConfig } from '@nx/webpack';
const config: ModuleFederationConfig = {
name: '${remote}',
remotes: ['${childRemote}'],
exposes: {
'./Routes': '${remote}/src/app/remote-entry/entry.routes.ts',
'./Module': '${remote}/src/app/remote-entry/entry.component.ts',
},
};
export default config;`
);
// Update e2e test to check the module
updateFile(
`${host}-e2e/src/e2e/app.cy.ts`,
`
describe('${host}', () => {
beforeEach(() => cy.visit('/${remote}'));
it('should display contain the remote library', () => {
expect(cy.get('div.childremote')).to.exist;
expect(cy.get('div.childremote').contains('shell is even'));
});
});
`
);
// Build host and remote
const buildOutput = await runCommandUntil(`build ${host}`, (output) =>
output.includes('Successfully ran target build')
);
await killProcessAndPorts(buildOutput.pid);
const remoteOutput = await runCommandUntil(`build ${remote}`, (output) =>
output.includes('Successfully ran target build')
);
await killProcessAndPorts(remoteOutput.pid);
if (runE2ETests()) {
const hostE2eResults = await runCommandUntil(
`e2e ${host}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);
await killProcessAndPorts(hostE2eResults.pid, hostPort, hostPort + 1);
}
}, 500_000);
});
|
1,881 | 0 | petrpan-code/nrwl/nx/e2e/angular-core | petrpan-code/nrwl/nx/e2e/angular-core/src/ng-add.test.ts | import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
getSelectedPackageManager,
packageInstall,
readJson,
runCLI,
runCommand,
runNgAdd,
runNgNew,
uniq,
updateFile,
} from '@nx/e2e/utils';
import { PackageManager } from 'nx/src/utils/package-manager';
describe('convert Angular CLI workspace to an Nx workspace', () => {
let project: string;
let packageManager: PackageManager;
// utility to manually add protractor since it's not generated
// in the latest Angular CLI versions, but older projects updated
// to latest versions might still have it
function addProtractor() {
updateFile('e2e/protractor.conf.js', 'exports.config = {};');
updateFile(
'e2e/tsconfig.json',
JSON.stringify({ extends: '../tsconfig.json' }, null, 2)
);
updateFile(
'e2e/src/app.e2e-spec.ts',
`describe('app', () => {
it('should pass', () => {
expect(true).toBe(true);
});
});`
);
const angularJson = readJson('angular.json');
angularJson.projects[project].architect.e2e = {
builder: '@angular-devkit/build-angular:protractor',
options: {
protractorConfig: 'e2e/protractor.conf.js',
devServerTarget: `${project}:serve`,
},
configurations: {
production: { devServerTarget: `${project}:serve:production` },
},
};
updateFile('angular.json', JSON.stringify(angularJson, null, 2));
}
function addCypress9() {
runNgAdd('@cypress/schematic', '--e2e-update', '1.7.0');
packageInstall('cypress', null, '^9.0.0');
}
function addCypress10() {
runNgAdd('@cypress/schematic', '--e2e', 'latest');
}
function addEsLint() {
runNgAdd('@angular-eslint/schematics', undefined, 'latest');
}
beforeEach(() => {
packageManager = getSelectedPackageManager();
// TODO: solve issues with pnpm and remove this fallback
packageManager = packageManager === 'pnpm' ? 'yarn' : packageManager;
project = runNgNew(packageManager);
packageInstall('nx', null, 'latest');
packageInstall('@nx/angular', null, 'latest');
});
afterEach(() => {
cleanupProject();
});
it('should generate a workspace', () => {
addProtractor();
// update package.json
const packageJson = readJson('package.json');
packageJson.description = 'some description';
updateFile('package.json', JSON.stringify(packageJson, null, 2));
// update tsconfig.json
const tsConfig = readJson('tsconfig.json');
tsConfig.compilerOptions.paths = { a: ['b'] };
updateFile('tsconfig.json', JSON.stringify(tsConfig, null, 2));
// add an extra script file
updateFile('src/scripts.js', 'const x = 1;');
// update angular.json
const angularJson = readJson('angular.json');
angularJson.projects[project].architect.build.options.scripts =
angularJson.projects[project].architect.test.options.scripts = [
'src/scripts.js',
];
angularJson.projects[project].architect.test.options.styles = [
'src/styles.css',
];
updateFile('angular.json', JSON.stringify(angularJson, null, 2));
// confirm that @nx dependencies do not exist yet
expect(packageJson.devDependencies['@nx/workspace']).not.toBeDefined();
// run ng add
runCLI('g @nx/angular:ng-add --default-base main');
// check that prettier config exits and that files have been moved
checkFilesExist(
'.vscode/extensions.json',
'.prettierrc',
`apps/${project}/src/main.ts`,
`apps/${project}/src/app/app.config.ts`,
`apps/${project}/src/app/app.component.ts`,
`apps/${project}/src/app/app.routes.ts`
);
// check the right VSCode extensions are recommended
expect(readJson('.vscode/extensions.json').recommendations).toEqual([
'angular.ng-template',
'nrwl.angular-console',
'dbaeumer.vscode-eslint',
'esbenp.prettier-vscode',
]);
// check package.json
const updatedPackageJson = readJson('package.json');
expect(updatedPackageJson.description).toEqual('some description');
expect(updatedPackageJson.scripts).toEqual({
ng: 'ng',
start: 'nx serve',
build: 'nx build',
watch: 'nx build --watch --configuration development',
test: 'nx test',
});
expect(updatedPackageJson.devDependencies['@nx/workspace']).toBeDefined();
expect(updatedPackageJson.devDependencies['@angular/cli']).toBeDefined();
// check nx.json
const nxJson = readJson('nx.json');
expect(nxJson).toEqual({
affected: {
defaultBase: 'main',
},
namedInputs: {
default: ['{projectRoot}/**/*', 'sharedGlobals'],
production: [
'default',
'!{projectRoot}/tsconfig.spec.json',
'!{projectRoot}/**/*.spec.[jt]s',
'!{projectRoot}/karma.conf.js',
],
sharedGlobals: [],
},
targetDefaults: {
build: {
dependsOn: ['^build'],
inputs: ['production', '^production'],
cache: true,
},
e2e: {
inputs: ['default', '^production'],
cache: true,
},
test: {
inputs: ['default', '^production', '{workspaceRoot}/karma.conf.js'],
cache: true,
},
},
});
// check angular.json does not exist
checkFilesDoNotExist('angular.json');
// check project configuration
const projectConfig = readJson(`apps/${project}/project.json`);
expect(projectConfig.sourceRoot).toEqual(`apps/${project}/src`);
expect(projectConfig.targets.build).toStrictEqual({
executor: '@angular-devkit/build-angular:application',
options: {
outputPath: `dist/apps/${project}`,
index: `apps/${project}/src/index.html`,
browser: `apps/${project}/src/main.ts`,
polyfills: [`zone.js`],
tsConfig: `apps/${project}/tsconfig.app.json`,
assets: [
`apps/${project}/src/favicon.ico`,
`apps/${project}/src/assets`,
],
styles: [`apps/${project}/src/styles.css`],
scripts: [`apps/${project}/src/scripts.js`],
},
configurations: {
production: {
budgets: [
{
type: 'initial',
maximumWarning: '500kb',
maximumError: '1mb',
},
{
type: 'anyComponentStyle',
maximumWarning: '2kb',
maximumError: '4kb',
},
],
outputHashing: 'all',
},
development: {
optimization: false,
extractLicenses: false,
sourceMap: true,
},
},
defaultConfiguration: 'production',
});
expect(projectConfig.targets.serve).toEqual({
executor: '@angular-devkit/build-angular:dev-server',
configurations: {
production: { buildTarget: `${project}:build:production` },
development: { buildTarget: `${project}:build:development` },
},
defaultConfiguration: 'development',
});
expect(projectConfig.targets.test).toStrictEqual({
executor: '@angular-devkit/build-angular:karma',
options: {
polyfills: [`zone.js`, `zone.js/testing`],
tsConfig: `apps/${project}/tsconfig.spec.json`,
assets: [
`apps/${project}/src/favicon.ico`,
`apps/${project}/src/assets`,
],
styles: [`apps/${project}/src/styles.css`],
scripts: [`apps/${project}/src/scripts.js`],
},
});
expect(projectConfig.targets.e2e).toBeUndefined();
// check e2e project config
const e2eProjectConfig = readJson(`apps/${project}-e2e/project.json`);
expect(e2eProjectConfig.targets.e2e).toEqual({
executor: '@angular-devkit/build-angular:protractor',
options: {
protractorConfig: `apps/${project}-e2e/protractor.conf.js`,
devServerTarget: `${project}:serve`,
},
configurations: {
production: {
devServerTarget: `${project}:serve:production`,
},
},
});
runCLI(`build ${project} --configuration production --outputHashing none`);
checkFilesExist(`dist/apps/${project}/browser/main.js`);
});
it('should handle a workspace with cypress v9', () => {
addCypress9();
runCLI('g @nx/angular:ng-add --skip-install');
const e2eProject = `${project}-e2e`;
//check e2e project files
checkFilesDoNotExist(
'cypress.json',
'cypress/tsconfig.json',
'cypress/integration/spec.ts',
'cypress/plugins/index.ts',
'cypress/support/commands.ts',
'cypress/support/index.ts'
);
checkFilesExist(
`apps/${e2eProject}/cypress.json`,
`apps/${e2eProject}/tsconfig.json`,
`apps/${e2eProject}/src/integration/spec.ts`,
`apps/${e2eProject}/src/plugins/index.ts`,
`apps/${e2eProject}/src/support/commands.ts`,
`apps/${e2eProject}/src/support/index.ts`
);
const projectConfig = readJson(`apps/${project}/project.json`);
expect(projectConfig.targets['cypress-run']).toBeUndefined();
expect(projectConfig.targets['cypress-open']).toBeUndefined();
expect(projectConfig.targets.e2e).toBeUndefined();
// check e2e project config
const e2eProjectConfig = readJson(`apps/${project}-e2e/project.json`);
expect(e2eProjectConfig.targets['cypress-run']).toEqual({
executor: '@nx/cypress:cypress',
options: {
devServerTarget: `${project}:serve`,
cypressConfig: `apps/${e2eProject}/cypress.json`,
},
configurations: {
production: {
devServerTarget: `${project}:serve:production`,
},
},
});
expect(e2eProjectConfig.targets['cypress-open']).toEqual({
executor: '@nx/cypress:cypress',
options: {
watch: true,
headless: false,
cypressConfig: `apps/${e2eProject}/cypress.json`,
},
});
expect(e2eProjectConfig.targets.e2e).toEqual({
executor: '@nx/cypress:cypress',
options: {
devServerTarget: `${project}:serve`,
watch: true,
headless: false,
cypressConfig: `apps/${e2eProject}/cypress.json`,
},
configurations: {
production: {
devServerTarget: `${project}:serve:production`,
},
},
});
});
it('should handle a workspace with cypress v10', () => {
addCypress10();
runCLI('g @nx/angular:ng-add --skip-install');
const e2eProject = `${project}-e2e`;
//check e2e project files
checkFilesDoNotExist(
'cypress.config.ts',
'cypress/tsconfig.json',
'cypress/e2e/spec.cy.ts',
'cypress/fixtures/example.json',
'cypress/support/commands.ts',
'cypress/support/e2e.ts'
);
checkFilesExist(
`apps/${e2eProject}/cypress.config.ts`,
`apps/${e2eProject}/tsconfig.json`,
`apps/${e2eProject}/src/e2e/spec.cy.ts`,
`apps/${e2eProject}/src/fixtures/example.json`,
`apps/${e2eProject}/src/support/commands.ts`,
`apps/${e2eProject}/src/support/e2e.ts`
);
const projectConfig = readJson(`apps/${project}/project.json`);
expect(projectConfig.targets['cypress-run']).toBeUndefined();
expect(projectConfig.targets['cypress-open']).toBeUndefined();
expect(projectConfig.targets.e2e).toBeUndefined();
// check e2e project config
const e2eProjectConfig = readJson(`apps/${project}-e2e/project.json`);
expect(e2eProjectConfig.targets['cypress-run']).toEqual({
executor: '@nx/cypress:cypress',
options: {
devServerTarget: `${project}:serve`,
cypressConfig: `apps/${e2eProject}/cypress.config.ts`,
},
configurations: {
production: {
devServerTarget: `${project}:serve:production`,
},
},
});
expect(e2eProjectConfig.targets['cypress-open']).toEqual({
executor: '@nx/cypress:cypress',
options: {
watch: true,
headless: false,
cypressConfig: `apps/${e2eProject}/cypress.config.ts`,
},
});
expect(e2eProjectConfig.targets.e2e).toEqual({
executor: '@nx/cypress:cypress',
options: {
devServerTarget: `${project}:serve`,
watch: true,
headless: false,
cypressConfig: `apps/${e2eProject}/cypress.config.ts`,
},
configurations: {
production: {
devServerTarget: `${project}:serve:production`,
},
},
});
});
// TODO(leo): The current Verdaccio setup fails to resolve older versions
// of @nx/* packages, the @angular-eslint/builder package depends on an
// older version of @nx/devkit so we skip this test for now.
it.skip('should handle a workspace with ESLint', () => {
addEsLint();
runCLI('g @nx/angular:ng-add');
checkFilesExist(`apps/${project}/.eslintrc.json`, `.eslintrc.json`);
const projectConfig = readJson(`apps/${project}/project.json`);
expect(projectConfig.targets.lint).toStrictEqual({
executor: '@nx/eslint:lint',
options: {
lintFilePatterns: [
`apps/${project}/src/**/*.ts`,
`apps/${project}/src/**/*.html`,
],
},
});
let output = runCLI(`lint ${project}`);
expect(output).toContain(`> nx run ${project}:lint`);
expect(output).toContain('All files pass linting.');
expect(output).toContain(
`Successfully ran target lint for project ${project}`
);
output = runCLI(`lint ${project}`);
expect(output).toContain(`> nx run ${project}:lint [local cache]`);
expect(output).toContain('All files pass linting.');
expect(output).toContain(
`Successfully ran target lint for project ${project}`
);
});
it('should support a workspace with multiple projects', () => {
// add other projects
const app1 = uniq('app1');
const lib1 = uniq('lib1');
runCommand(`ng g @schematics/angular:application ${app1} --no-interactive`);
runCommand(`ng g @schematics/angular:library ${lib1} --no-interactive`);
runCLI('g @nx/angular:ng-add');
// check angular.json does not exist
checkFilesDoNotExist('angular.json');
// check building project
let output = runCLI(`build ${project} --outputHashing none`);
expect(output).toContain(
`> nx run ${project}:build:production --outputHashing none`
);
expect(output).toContain(
`Successfully ran target build for project ${project}`
);
checkFilesExist(`dist/apps/${project}/browser/main.js`);
output = runCLI(`build ${project} --outputHashing none`);
expect(output).toContain(
`> nx run ${project}:build:production --outputHashing none [local cache]`
);
expect(output).toContain(
`Successfully ran target build for project ${project}`
);
// check building app1
output = runCLI(`build ${app1} --outputHashing none`);
expect(output).toContain(
`> nx run ${app1}:build:production --outputHashing none`
);
expect(output).toContain(
`Successfully ran target build for project ${app1}`
);
checkFilesExist(`dist/apps/${app1}/browser/main.js`);
output = runCLI(`build ${app1} --outputHashing none`);
expect(output).toContain(
`> nx run ${app1}:build:production --outputHashing none [local cache]`
);
expect(output).toContain(
`Successfully ran target build for project ${app1}`
);
// check building lib1
output = runCLI(`build ${lib1}`);
expect(output).toContain(`> nx run ${lib1}:build:production`);
expect(output).toContain(
`Successfully ran target build for project ${lib1}`
);
checkFilesExist(`dist/${lib1}/package.json`);
output = runCLI(`build ${lib1}`);
expect(output).toContain(
`> nx run ${lib1}:build:production [local cache]`
);
expect(output).toContain(
`Successfully ran target build for project ${lib1}`
);
});
});
|
1,882 | 0 | petrpan-code/nrwl/nx/e2e/angular-core | petrpan-code/nrwl/nx/e2e/angular-core/src/projects.test.ts | import { names } from '@nx/devkit';
import {
checkFilesExist,
cleanupProject,
getSize,
killPorts,
killProcessAndPorts,
newProject,
readFile,
removeFile,
runCLI,
runCommandUntil,
runE2ETests,
tmpProjPath,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { join, normalize } from 'path';
describe('Angular Projects', () => {
let proj: string;
const app1 = uniq('app1');
const lib1 = uniq('lib1');
let app1DefaultModule: string;
let app1DefaultComponentTemplate: string;
beforeAll(() => {
proj = newProject();
runCLI(
`generate @nx/angular:app ${app1} --no-standalone --bundler=webpack --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/angular:lib ${lib1} --no-standalone --add-module-spec --project-name-and-root-format=as-provided --no-interactive`
);
app1DefaultModule = readFile(`${app1}/src/app/app.module.ts`);
app1DefaultComponentTemplate = readFile(
`${app1}/src/app/app.component.html`
);
});
afterEach(() => {
updateFile(`${app1}/src/app/app.module.ts`, app1DefaultModule);
updateFile(
`${app1}/src/app/app.component.html`,
app1DefaultComponentTemplate
);
});
afterAll(() => cleanupProject());
it('should successfully generate apps and libs and work correctly', async () => {
const standaloneApp = uniq('standalone-app');
runCLI(
`generate @nx/angular:app ${standaloneApp} --directory=my-dir/${standaloneApp} --bundler=webpack --project-name-and-root-format=as-provided --no-interactive`
);
const esbuildApp = uniq('esbuild-app');
runCLI(
`generate @nx/angular:app ${esbuildApp} --bundler=esbuild --directory=my-dir/${esbuildApp} --project-name-and-root-format=as-provided --no-interactive`
);
updateFile(
`${app1}/src/app/app.module.ts`,
`
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { appRoutes } from './app.routes';
import { NxWelcomeComponent } from './nx-welcome.component';
import { ${names(lib1).className}Module } from '@${proj}/${lib1}';
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes, { initialNavigation: 'enabledBlocking' }),
${names(lib1).className}Module
],
declarations: [AppComponent, NxWelcomeComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
`
);
// check build
runCLI(
`run-many --target build --projects=${app1},${standaloneApp},${esbuildApp} --parallel --prod --output-hashing none`
);
checkFilesExist(`dist/${app1}/main.js`);
checkFilesExist(`dist/my-dir/${standaloneApp}/main.js`);
checkFilesExist(`dist/my-dir/${esbuildApp}/browser/main.js`);
// This is a loose requirement because there are a lot of
// influences external from this project that affect this.
const es2015BundleSize = getSize(tmpProjPath(`dist/${app1}/main.js`));
console.log(
`The current es2015 bundle size is ${es2015BundleSize / 1000} KB`
);
expect(es2015BundleSize).toBeLessThanOrEqual(220000);
// check unit tests
runCLI(
`run-many --target test --projects=${app1},${standaloneApp},${esbuildApp},${lib1} --parallel`
);
// check e2e tests
if (runE2ETests()) {
const e2eResults = runCLI(`e2e ${app1}-e2e --no-watch`);
expect(e2eResults).toContain('All specs passed!');
expect(await killPorts()).toBeTruthy();
}
const appPort = 4207;
const process = await runCommandUntil(
`serve ${app1} -- --port=${appPort}`,
(output) => output.includes(`listening on localhost:${appPort}`)
);
// port and process cleanup
await killProcessAndPorts(process.pid, appPort);
const esbProcess = await runCommandUntil(
`serve ${esbuildApp} -- --port=${appPort}`,
(output) =>
output.includes(`Application bundle generation complete`) &&
output.includes(`localhost:${appPort}`)
);
// port and process cleanup
await killProcessAndPorts(esbProcess.pid, appPort);
}, 1000000);
// TODO: enable this when tests are passing again.
xit('should successfully work with playwright for e2e tests', async () => {
const app = uniq('app');
runCLI(
`generate @nx/angular:app ${app} --e2eTestRunner=playwright --project-name-and-root-format=as-provided --no-interactive`
);
if (runE2ETests()) {
const e2eResults = runCLI(`e2e ${app}-e2e`);
expect(e2eResults).toContain(
`Successfully ran target e2e for project ${app}-e2e`
);
expect(await killPorts()).toBeTruthy();
}
}, 1000000);
it('should lint correctly with eslint and handle external HTML files and inline templates', async () => {
// check apps and lib pass linting for initial generated code
runCLI(`run-many --target lint --projects=${app1},${lib1} --parallel`);
// External HTML template file
const templateWhichFailsBananaInBoxLintCheck = `<div ([foo])="bar"></div>`;
updateFile(
`${app1}/src/app/app.component.html`,
templateWhichFailsBananaInBoxLintCheck
);
// Inline template within component.ts file
const wrappedAsInlineTemplate = `
import { Component } from '@angular/core';
@Component({
selector: 'inline-template-component',
template: \`
${templateWhichFailsBananaInBoxLintCheck}
\`,
})
export class InlineTemplateComponent {}
`;
updateFile(
`${app1}/src/app/inline-template.component.ts`,
wrappedAsInlineTemplate
);
const appLintStdOut = runCLI(`lint ${app1}`, {
silenceError: true,
});
expect(appLintStdOut).toContain(
normalize(`${app1}/src/app/app.component.html`)
);
expect(appLintStdOut).toContain(`1:6`);
expect(appLintStdOut).toContain(`Invalid binding syntax`);
expect(appLintStdOut).toContain(
normalize(`${app1}/src/app/inline-template.component.ts`)
);
expect(appLintStdOut).toContain(`5:19`);
expect(appLintStdOut).toContain(
`The selector should start with one of these prefixes`
);
expect(appLintStdOut).toContain(`7:16`);
expect(appLintStdOut).toContain(`Invalid binding syntax`);
// cleanup added component
removeFile(`${app1}/src/app/inline-template.component.ts`);
}, 1000000);
it('should build the dependent buildable lib and its child lib, as well as the app', async () => {
// ARRANGE
const esbuildApp = uniq('esbuild-app');
runCLI(
`generate @nx/angular:app ${esbuildApp} --bundler=esbuild --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
const buildableLib = uniq('buildlib1');
const buildableChildLib = uniq('buildlib2');
runCLI(
`generate @nx/angular:library ${buildableLib} --buildable=true --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/angular:library ${buildableChildLib} --buildable=true --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
// update the app module to include a ref to the buildable lib
updateFile(
`${app1}/src/app/app.module.ts`,
`
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { appRoutes } from './app.routes';
import { NxWelcomeComponent } from './nx-welcome.component';
import {${
names(buildableLib).className
}Module} from '@${proj}/${buildableLib}';
@NgModule({
declarations: [AppComponent, NxWelcomeComponent],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes, { initialNavigation: 'enabledBlocking' }),
${names(buildableLib).className}Module
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
`
);
updateFile(
`${esbuildApp}/src/app/app.module.ts`,
`
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { appRoutes } from './app.routes';
import { NxWelcomeComponent } from './nx-welcome.component';
import {${
names(buildableLib).className
}Module} from '@${proj}/${buildableLib}';
@NgModule({
declarations: [AppComponent, NxWelcomeComponent],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes, { initialNavigation: 'enabledBlocking' }),
${names(buildableLib).className}Module
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
`
);
// update the buildable lib module to include a ref to the buildable child lib
updateFile(
`${buildableLib}/src/lib/${names(buildableLib).fileName}.module.ts`,
`
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ${
names(buildableChildLib).className
}Module } from '@${proj}/${buildableChildLib}';
@NgModule({
imports: [CommonModule, ${names(buildableChildLib).className}Module],
})
export class ${names(buildableLib).className}Module {}
`
);
// update the project.json
updateJson(join(app1, 'project.json'), (config) => {
config.targets.build.executor = '@nx/angular:webpack-browser';
config.targets.build.options = {
...config.targets.build.options,
buildLibsFromSource: false,
};
return config;
});
updateJson(join(esbuildApp, 'project.json'), (config) => {
config.targets.build.executor = '@nx/angular:browser-esbuild';
config.targets.build.options = {
...config.targets.build.options,
outputPath: `dist/${esbuildApp}`,
main: config.targets.build.options.browser,
browser: undefined,
buildLibsFromSource: false,
};
return config;
});
// ACT
const libOutput = runCLI(`build ${app1} --configuration=development`);
const esbuildLibOutput = runCLI(
`build ${esbuildApp} --configuration=development`
);
// ASSERT
expect(libOutput).toContain(
`Building entry point '@${proj}/${buildableLib}'`
);
expect(libOutput).toContain(`nx run ${app1}:build:development`);
// to proof it has been built from source the "main.js" should actually contain
// the path to dist
const mainBundle = readFile(`dist/${app1}/main.js`);
expect(mainBundle).toContain(`dist/${buildableLib}`);
const mainEsBuildBundle = readFile(`dist/${esbuildApp}/main.js`);
expect(mainEsBuildBundle).toContain(`dist/${buildableLib}`);
});
it('should build publishable libs successfully', () => {
// ARRANGE
const lib = uniq('lib');
const childLib = uniq('child');
const entryPoint = uniq('entrypoint');
runCLI(
`generate @nx/angular:lib ${lib} --publishable --importPath=@${proj}/${lib} --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/angular:secondary-entry-point --name=${entryPoint} --library=${lib} --no-interactive`
);
runCLI(
`generate @nx/angular:library ${childLib} --publishable=true --importPath=@${proj}/${childLib} --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/angular:secondary-entry-point --name=sub --library=${childLib} --no-interactive`
);
const moduleContent = `
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ${
names(childLib).className
}Module } from '@${proj}/${childLib}';
import { SubModule } from '@${proj}/${childLib}/sub';
@NgModule({
imports: [CommonModule, ${names(childLib).className}Module, SubModule]
})
export class ${names(lib).className}Module {}`;
updateFile(`${lib}/src/lib/${lib}.module.ts`, moduleContent);
// ACT
const buildOutput = runCLI(`build ${lib}`);
// ASSERT
expect(buildOutput).toContain(`Building entry point '@${proj}/${lib}'`);
expect(buildOutput).toContain(
`Building entry point '@${proj}/${lib}/${entryPoint}'`
);
expect(buildOutput).toContain('Successfully ran target build');
});
it('should support generating projects with --project-name-and-root-format=derived', () => {
const appName = uniq('app1');
const libName = uniq('lib1');
runCLI(
`generate @nx/angular:app ${appName} --no-standalone --project-name-and-root-format=derived --no-interactive`
);
// check files are generated with the layout directory ("apps/")
checkFilesExist(`apps/${appName}/src/app/app.module.ts`);
// check build works
expect(runCLI(`build ${appName}`)).toContain(
`Successfully ran target build for project ${appName}`
);
// check tests pass
const appTestResult = runCLI(`test ${appName}`);
expect(appTestResult).toContain(
`Successfully ran target test for project ${appName}`
);
runCLI(
`generate @nx/angular:lib ${libName} --no-standalone --buildable --project-name-and-root-format=derived`
);
// check files are generated with the layout directory ("libs/")
checkFilesExist(
`libs/${libName}/src/index.ts`,
`libs/${libName}/src/lib/${libName}.module.ts`
);
// check build works
expect(runCLI(`build ${libName}`)).toContain(
`Successfully ran target build for project ${libName}`
);
// check tests pass
const libTestResult = runCLI(`test ${libName}`);
expect(libTestResult).toContain(
`Successfully ran target test for project ${libName}`
);
}, 500_000);
it('should support generating libraries with a scoped name when --project-name-and-root-format=as-provided', () => {
const libName = uniq('@my-org/lib1');
// assert scoped project names are not supported when --project-name-and-root-format=derived
expect(() =>
runCLI(
`generate @nx/angular:lib ${libName} --buildable --no-standalone --project-name-and-root-format=derived`
)
).toThrow();
runCLI(
`generate @nx/angular:lib ${libName} --buildable --no-standalone --project-name-and-root-format=as-provided`
);
// check files are generated without the layout directory ("libs/") and
// using the project name as the directory when no directory is provided
checkFilesExist(
`${libName}/src/index.ts`,
`${libName}/src/lib/${libName.split('/')[1]}.module.ts`
);
// check build works
expect(runCLI(`build ${libName}`)).toContain(
`Successfully ran target build for project ${libName}`
);
// check tests pass
const libTestResult = runCLI(`test ${libName}`);
expect(libTestResult).toContain(
`Successfully ran target test for project ${libName}`
);
}, 500_000);
});
|
1,887 | 0 | petrpan-code/nrwl/nx/e2e/angular-extensions | petrpan-code/nrwl/nx/e2e/angular-extensions/src/cypress-component-tests.test.ts | import {
checkFilesDoNotExist,
cleanupProject,
createFile,
newProject,
runCLI,
runE2ETests,
uniq,
updateFile,
removeFile,
checkFilesExist,
updateJson,
} from '../../utils';
import { names } from '@nx/devkit';
import { join } from 'path';
describe('Angular Cypress Component Tests', () => {
let projectName: string;
const appName = uniq('cy-angular-app');
const usedInAppLibName = uniq('cy-angular-lib');
const buildableLibName = uniq('cy-angular-buildable-lib');
beforeAll(async () => {
projectName = newProject({ name: uniq('cy-ng') });
createApp(appName);
createLib(projectName, appName, usedInAppLibName);
useLibInApp(projectName, appName, usedInAppLibName);
createBuildableLib(projectName, buildableLibName);
await useWorkspaceAssetsInApp(appName);
});
afterAll(() => cleanupProject());
it('should test app', () => {
runCLI(
`generate @nx/angular:cypress-component-configuration --project=${appName} --generate-tests --no-interactive`
);
if (runE2ETests()) {
expect(runCLI(`component-test ${appName} --no-watch`)).toContain(
'All specs passed!'
);
}
}, 300_000);
it('should successfully component test lib being used in app', () => {
runCLI(
`generate @nx/angular:cypress-component-configuration --project=${usedInAppLibName} --generate-tests --no-interactive`
);
if (runE2ETests()) {
expect(runCLI(`component-test ${usedInAppLibName} --no-watch`)).toContain(
'All specs passed!'
);
}
}, 300_000);
it('should test buildable lib not being used in app', () => {
expect(() => {
// should error since no edge in graph between lib and app
runCLI(
`generate @nx/angular:cypress-component-configuration --project=${buildableLibName} --generate-tests --no-interactive`
);
}).toThrow();
updateTestToAssertTailwindIsNotApplied(buildableLibName);
runCLI(
`generate @nx/angular:cypress-component-configuration --project=${buildableLibName} --generate-tests --build-target=${appName}:build --no-interactive`
);
if (runE2ETests()) {
expect(runCLI(`component-test ${buildableLibName} --no-watch`)).toContain(
'All specs passed!'
);
}
// add tailwind
runCLI(`generate @nx/angular:setup-tailwind --project=${buildableLibName}`);
updateFile(
`${buildableLibName}/src/lib/input/input.component.cy.ts`,
(content) => {
// text-green-500 should now apply
return content.replace('rgb(0, 0, 0)', 'rgb(34, 197, 94)');
}
);
updateFile(
`${buildableLibName}/src/lib/input-standalone/input-standalone.component.cy.ts`,
(content) => {
// text-green-500 should now apply
return content.replace('rgb(0, 0, 0)', 'rgb(34, 197, 94)');
}
);
if (runE2ETests()) {
expect(runCLI(`component-test ${buildableLibName} --no-watch`)).toContain(
'All specs passed!'
);
checkFilesDoNotExist(`tmp${buildableLibName}/ct-styles.css`);
}
}, 300_000);
it('should test lib with implicit dep on buildTarget', () => {
// creates graph like buildableLib -> lib -> app
// updates the apps styles and they should apply to the buildableLib
// even though app is not directly connected to buildableLib
useBuildableLibInLib(projectName, buildableLibName, usedInAppLibName);
updateBuilableLibTestsToAssertAppStyles(appName, buildableLibName);
if (runE2ETests()) {
expect(runCLI(`component-test ${buildableLibName} --no-watch`)).toContain(
'All specs passed!'
);
}
});
it('should use root level tailwinds config', () => {
useRootLevelTailwindConfig(join(buildableLibName, 'tailwind.config.js'));
checkFilesExist('tailwind.config.js');
checkFilesDoNotExist(`${buildableLibName}/tailwind.config.js`);
if (runE2ETests()) {
expect(runCLI(`component-test ${buildableLibName} --no-watch`)).toContain(
'All specs passed!'
);
}
});
});
function createApp(appName: string) {
runCLI(
`generate @nx/angular:app ${appName} --bundler=webpack --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/angular:component fancy-component --project=${appName} --no-interactive`
);
}
function createLib(projectName: string, appName: string, libName: string) {
runCLI(
`generate @nx/angular:lib ${libName} --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/angular:component btn --project=${libName} --inlineTemplate --inlineStyle --export --no-interactive`
);
runCLI(
`generate @nx/angular:component btn-standalone --project=${libName} --inlineTemplate --inlineStyle --export --standalone --no-interactive`
);
updateFile(
`${libName}/src/lib/btn/btn.component.ts`,
`
import { Component, Input } from '@angular/core';
@Component({
selector: '${projectName}-btn',
template: '<button class="text-green-500">{{text}}</button>',
styles: []
})
export class BtnComponent {
@Input() text = 'something';
}
`
);
updateFile(
`${libName}/src/lib/btn-standalone/btn-standalone.component.ts`,
`
import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: '${projectName}-btn-standalone',
standalone: true,
imports: [CommonModule],
template: '<button class="text-green-500">standlone-{{text}}</button>',
styles: [],
})
export class BtnStandaloneComponent {
@Input() text = 'something';
}
`
);
}
function createBuildableLib(projectName: string, libName: string) {
// create lib
runCLI(
`generate @nx/angular:lib ${libName} --buildable --project-name-and-root-format=as-provided --no-interactive`
);
// create cmp for lib
runCLI(
`generate @nx/angular:component input --project=${libName} --inlineTemplate --inlineStyle --export --no-interactive`
);
// create standlone cmp for lib
runCLI(
`generate @nx/angular:component input-standalone --project=${libName} --inlineTemplate --inlineStyle --export --standalone --no-interactive`
);
// update cmp implmentation to use tailwind clasasserting in tests
updateFile(
`${libName}/src/lib/input/input.component.ts`,
`
import {Component, Input} from '@angular/core';
@Component({
selector: '${projectName}-input',
template: \`<label class="text-green-500">Email: <input class="border-blue-500" type="email" [readOnly]="readOnly"></label>\`,
styles : []
})
export class InputComponent{
@Input() readOnly = false;
}
`
);
updateFile(
`${libName}/src/lib/input-standalone/input-standalone.component.ts`,
`
import {Component, Input} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
selector: '${projectName}-input-standalone',
standalone: true,
imports: [CommonModule],
template: \`<label class="text-green-500">Email: <input class="border-blue-500" type="email" [readOnly]="readOnly"></label>\`,
styles : []
})
export class InputStandaloneComponent{
@Input() readOnly = false;
}
`
);
}
function useLibInApp(projectName: string, appName: string, libName: string) {
createFile(
`${appName}/src/app/app.component.html`,
`
<${projectName}-btn></${projectName}-btn>
<${projectName}-btn-standalone></${projectName}-btn-standalone>
<${projectName}-nx-welcome></${projectName}-nx-welcome>
`
);
const btnModuleName = names(libName).className;
updateFile(
`${appName}/src/app/app.component.scss`,
`
@use 'styleguide' as *;
h1 {
@include headline;
}`
);
updateFile(
`${appName}/src/app/app.module.ts`,
`
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {${btnModuleName}Module} from "@${projectName}/${libName}";
import { AppComponent } from './app.component';
import { NxWelcomeComponent } from './nx-welcome.component';
@NgModule({
declarations: [AppComponent, NxWelcomeComponent],
imports: [BrowserModule, ${btnModuleName}Module],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
`
);
}
async function useWorkspaceAssetsInApp(appName: string) {
// make sure assets from the workspace root work.
createFile('libs/assets/data.json', JSON.stringify({ data: 'data' }));
createFile(
'assets/styles/styleguide.scss',
`
@mixin headline {
font-weight: bold;
color: darkkhaki;
background: lightcoral;
font-weight: 24px;
}
`
);
updateJson(join(appName, 'project.json'), (config) => {
config.targets['build'].options.stylePreprocessorOptions = {
includePaths: ['assets/styles'],
};
config.targets['build'].options.assets.push({
glob: '**/*',
input: 'libs/assets',
output: 'assets',
});
return config;
});
}
function updateTestToAssertTailwindIsNotApplied(libName: string) {
createFile(
`${libName}/src/lib/input/input.component.cy.ts`,
`
import { MountConfig } from 'cypress/angular';
import { InputComponent } from './input.component';
describe(InputComponent.name, () => {
const config: MountConfig<InputComponent> = {
declarations: [],
imports: [],
providers: [],
};
it('renders', () => {
cy.mount(InputComponent, config);
// make sure tailwind isn't getting applied
cy.get('label').should('have.css', 'color', 'rgb(0, 0, 0)');
});
it('should be readonly', () => {
cy.mount(InputComponent, {
...config,
componentProperties: {
readOnly: true,
},
});
cy.get('input').should('have.attr', 'readonly');
});
});
`
);
createFile(
`${libName}/src/lib/input-standalone/input-standalone.component.cy.ts`,
`
import { MountConfig } from 'cypress/angular';
import { InputStandaloneComponent } from './input-standalone.component';
describe(InputStandaloneComponent.name, () => {
const config: MountConfig<InputStandaloneComponent> = {
declarations: [],
imports: [],
providers: [],
};
it('renders', () => {
cy.mount(InputStandaloneComponent, config);
// make sure tailwind isn't getting applied
cy.get('label').should('have.css', 'color', 'rgb(0, 0, 0)');
});
it('should be readonly', () => {
cy.mount(InputStandaloneComponent, {
...config,
componentProperties: {
readOnly: true,
},
});
cy.get('input').should('have.attr', 'readonly');
});
});
`
);
}
function useBuildableLibInLib(
projectName: string,
buildableLibName: string,
libName: string
) {
const buildLibNames = names(buildableLibName);
// use the buildable lib in lib so now buildableLib has an indirect dep on app
updateFile(
`${libName}/src/lib/btn-standalone/btn-standalone.component.ts`,
`
import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { InputStandaloneComponent } from '@${projectName}/${buildLibNames.fileName}';
@Component({
selector: '${projectName}-btn-standalone',
standalone: true,
imports: [CommonModule, InputStandaloneComponent],
template: '<button class="text-green-500">standlone-{{text}}</button>${projectName} <${projectName}-input-standalone></${projectName}-input-standalone>',
styles: [],
})
export class BtnStandaloneComponent {
@Input() text = 'something';
}
`
);
}
function updateBuilableLibTestsToAssertAppStyles(
appName: string,
buildableLibName: string
) {
updateFile(`${appName}/src/styles.css`, `label {color: pink !important;}`);
removeFile(`${buildableLibName}/src/lib/input/input.component.cy.ts`);
updateFile(
`${buildableLibName}/src/lib/input-standalone/input-standalone.component.cy.ts`,
(content) => {
// app styles should now apply
return content.replace('rgb(34, 197, 94)', 'rgb(255, 192, 203)');
}
);
}
function useRootLevelTailwindConfig(existingConfigPath: string) {
createFile(
'tailwind.config.js',
`const { join } = require('path');
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [join(__dirname, '**/*.{html,js,ts}')],
theme: {
extend: {},
},
plugins: [],
};
`
);
removeFile(existingConfigPath);
}
|
1,888 | 0 | petrpan-code/nrwl/nx/e2e/angular-extensions | petrpan-code/nrwl/nx/e2e/angular-extensions/src/misc.test.ts | import {
checkFilesExist,
cleanupProject,
newProject,
readFile,
runCLI,
uniq,
updateFile,
} from '@nx/e2e/utils';
import { classify } from '@nx/devkit/src/utils/string-utils';
describe('Move Angular Project', () => {
let proj: string;
let app1: string;
let app2: string;
let newPath: string;
beforeAll(() => {
proj = newProject();
app1 = uniq('app1');
app2 = uniq('app2');
newPath = `subfolder/${app2}`;
runCLI(
`generate @nx/angular:app ${app1} --project-name-and-root-format=as-provided --no-interactive`
);
});
afterAll(() => cleanupProject());
/**
* Tries moving an app from ${app1} -> subfolder/${app2}
*/
it('should work for apps', () => {
const moveOutput = runCLI(
`generate @nx/angular:move --project ${app1} ${newPath} --project-name-and-root-format=as-provided`
);
// just check the output
expect(moveOutput).toContain(`DELETE ${app1}`);
expect(moveOutput).toContain(`CREATE ${newPath}/jest.config.ts`);
expect(moveOutput).toContain(`CREATE ${newPath}/tsconfig.app.json`);
expect(moveOutput).toContain(`CREATE ${newPath}/tsconfig.json`);
expect(moveOutput).toContain(`CREATE ${newPath}/tsconfig.spec.json`);
expect(moveOutput).toContain(`CREATE ${newPath}/.eslintrc.json`);
expect(moveOutput).toContain(`CREATE ${newPath}/src/favicon.ico`);
expect(moveOutput).toContain(`CREATE ${newPath}/src/index.html`);
expect(moveOutput).toContain(`CREATE ${newPath}/src/main.ts`);
expect(moveOutput).toContain(`CREATE ${newPath}/src/styles.css`);
expect(moveOutput).toContain(`CREATE ${newPath}/src/test-setup.ts`);
expect(moveOutput).toContain(
`CREATE ${newPath}/src/app/app.component.html`
);
expect(moveOutput).toContain(`CREATE ${newPath}/src/app/app.component.ts`);
expect(moveOutput).toContain(`CREATE ${newPath}/src/app/app.config.ts`);
expect(moveOutput).toContain(`CREATE ${newPath}/src/assets/.gitkeep`);
});
/**
* Tries moving an e2e project from ${app1} -> ${newPath}
*/
it('should work for e2e projects w/custom cypress config', () => {
// by default the cypress config doesn't contain any app specific paths
// create a custom config with some app specific paths
updateFile(
`${app1}-e2e/cypress.config.ts`,
`
import { defineConfig } from 'cypress';
import { nxE2EPreset } from '@nx/cypress/plugins/cypress-preset';
export default defineConfig({
e2e: {
...nxE2EPreset(__dirname),
videosFolder: '../dist/cypress/${app1}-e2e/videos',
screenshotsFolder: '../dist/cypress/${app1}-e2e/screenshots',
},
});
`
);
const moveOutput = runCLI(
`generate @nx/angular:move --projectName=${app1}-e2e --destination=${newPath}-e2e --project-name-and-root-format=as-provided`
);
// just check that the cypress.config.ts is updated correctly
const cypressConfigPath = `${newPath}-e2e/cypress.config.ts`;
expect(moveOutput).toContain(`CREATE ${cypressConfigPath}`);
checkFilesExist(cypressConfigPath);
const cypressConfig = readFile(cypressConfigPath);
expect(cypressConfig).toContain(`../../dist/cypress/${newPath}-e2e/videos`);
expect(cypressConfig).toContain(
`../../dist/cypress/${newPath}-e2e/screenshots`
);
});
/**
* Tries moving a library from ${lib} -> shared/${lib}
*/
it('should work for libraries', () => {
const lib1 = uniq('mylib');
const lib2 = uniq('mylib');
runCLI(
`generate @nx/angular:lib ${lib1} --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
/**
* Create a library which imports the module from the other lib
*/
runCLI(
`generate @nx/angular:lib ${lib2} --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
updateFile(
`${lib2}/src/lib/${lib2}.module.ts`,
`import { ${classify(lib1)}Module } from '@${proj}/${lib1}';
export class ExtendedModule extends ${classify(lib1)}Module { }`
);
const moveOutput = runCLI(
`generate @nx/angular:move --projectName=${lib1} --destination=shared/${lib1} --newProjectName=shared-${lib1} --project-name-and-root-format=as-provided`
);
const newPath = `shared/${lib1}`;
const newModule = `Shared${classify(lib1)}Module`;
const testSetupPath = `${newPath}/src/test-setup.ts`;
expect(moveOutput).toContain(`CREATE ${testSetupPath}`);
checkFilesExist(testSetupPath);
const modulePath = `${newPath}/src/lib/shared-${lib1}.module.ts`;
expect(moveOutput).toContain(`CREATE ${modulePath}`);
checkFilesExist(modulePath);
const moduleFile = readFile(modulePath);
expect(moduleFile).toContain(`export class ${newModule}`);
const indexPath = `${newPath}/src/index.ts`;
expect(moveOutput).toContain(`CREATE ${indexPath}`);
checkFilesExist(indexPath);
const index = readFile(indexPath);
expect(index).toContain(`export * from './lib/shared-${lib1}.module'`);
/**
* Check that the import in lib2 has been updated
*/
const lib2FilePath = `${lib2}/src/lib/${lib2}.module.ts`;
const lib2File = readFile(lib2FilePath);
expect(lib2File).toContain(
`import { ${newModule} } from '@${proj}/shared-${lib1}';`
);
expect(lib2File).toContain(`extends ${newModule}`);
});
it('should move projects correctly with --project-name-and-root-format=derived', () => {
const lib1 = uniq('mylib');
const lib2 = uniq('mylib');
runCLI(
`generate @nx/angular:lib ${lib1} --no-standalone --project-name-and-root-format=derived --no-interactive`
);
/**
* Create a library which imports the module from the other lib
*/
runCLI(
`generate @nx/angular:lib ${lib2} --no-standalone --project-name-and-root-format=derived --no-interactive`
);
updateFile(
`libs/${lib2}/src/lib/${lib2}.module.ts`,
`import { ${classify(lib1)}Module } from '@${proj}/${lib1}';
export class ExtendedModule extends ${classify(lib1)}Module { }`
);
const moveOutput = runCLI(
`generate @nx/angular:move --projectName=${lib1} --destination=shared/${lib1} --project-name-and-root-format=derived`
);
const newPath = `libs/shared/${lib1}`;
const newModule = `Shared${classify(lib1)}Module`;
const testSetupPath = `${newPath}/src/test-setup.ts`;
expect(moveOutput).toContain(`CREATE ${testSetupPath}`);
checkFilesExist(testSetupPath);
const modulePath = `${newPath}/src/lib/shared-${lib1}.module.ts`;
expect(moveOutput).toContain(`CREATE ${modulePath}`);
checkFilesExist(modulePath);
const moduleFile = readFile(modulePath);
expect(moduleFile).toContain(`export class ${newModule}`);
const indexPath = `${newPath}/src/index.ts`;
expect(moveOutput).toContain(`CREATE ${indexPath}`);
checkFilesExist(indexPath);
const index = readFile(indexPath);
expect(index).toContain(`export * from './lib/shared-${lib1}.module'`);
/**
* Check that the import in lib2 has been updated
*/
const lib2FilePath = `libs/${lib2}/src/lib/${lib2}.module.ts`;
const lib2File = readFile(lib2FilePath);
expect(lib2File).toContain(
`import { ${newModule} } from '@${proj}/shared/${lib1}';`
);
expect(lib2File).toContain(`extends ${newModule}`);
});
});
|
1,889 | 0 | petrpan-code/nrwl/nx/e2e/angular-extensions | petrpan-code/nrwl/nx/e2e/angular-extensions/src/ngrx.test.ts | import {
cleanupProject,
expectTestsPass,
getSelectedPackageManager,
newProject,
readJson,
runCLI,
runCLIAsync,
uniq,
} from '@nx/e2e/utils';
describe('Angular Package', () => {
describe('ngrx', () => {
beforeAll(() => {
newProject();
});
afterAll(() => {
cleanupProject();
});
it('should work', async () => {
const myapp = uniq('myapp');
runCLI(
`generate @nx/angular:app ${myapp} --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
// Generate root ngrx state management
runCLI(
`generate @nx/angular:ngrx users --parent=${myapp}/src/app/app.module.ts --root --minimal=false`
);
const packageJson = readJson('package.json');
expect(packageJson.dependencies['@ngrx/store']).toBeDefined();
expect(packageJson.dependencies['@ngrx/effects']).toBeDefined();
expect(packageJson.dependencies['@ngrx/router-store']).toBeDefined();
expect(packageJson.devDependencies['@ngrx/store-devtools']).toBeDefined();
const mylib = uniq('mylib');
// Generate feature library and ngrx state within that library
runCLI(
`g @nx/angular:lib ${mylib} --prefix=fl --no-standalone --project-name-and-root-format=as-provided`
);
runCLI(
`generate @nx/angular:ngrx flights --parent=${mylib}/src/lib/${mylib}.module.ts --facade`
);
expect(runCLI(`build ${myapp}`)).toMatch(/main-[a-zA-Z0-9]+\.js/);
expectTestsPass(await runCLIAsync(`test ${myapp} --no-watch`));
// TODO: remove this condition
if (getSelectedPackageManager() !== 'pnpm') {
expectTestsPass(await runCLIAsync(`test ${mylib} --no-watch`));
}
}, 1000000);
it('should work with creators', async () => {
const myapp = uniq('myapp');
runCLI(
`generate @nx/angular:app ${myapp} --routing --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
// Generate root ngrx state management
runCLI(
`generate @nx/angular:ngrx users --parent=${myapp}/src/app/app.module.ts --root`
);
const packageJson = readJson('package.json');
expect(packageJson.dependencies['@ngrx/entity']).toBeDefined();
expect(packageJson.dependencies['@ngrx/store']).toBeDefined();
expect(packageJson.dependencies['@ngrx/effects']).toBeDefined();
expect(packageJson.dependencies['@ngrx/router-store']).toBeDefined();
expect(packageJson.devDependencies['@ngrx/schematics']).toBeDefined();
expect(packageJson.devDependencies['@ngrx/store-devtools']).toBeDefined();
const mylib = uniq('mylib');
// Generate feature library and ngrx state within that library
runCLI(
`g @nx/angular:lib ${mylib} --prefix=fl --no-standalone --project-name-and-root-format=as-provided`
);
const flags = `--facade --barrels`;
runCLI(
`generate @nx/angular:ngrx flights --parent=${mylib}/src/lib/${mylib}.module.ts ${flags}`
);
expect(runCLI(`build ${myapp}`)).toMatch(/main-[a-zA-Z0-9]+\.js/);
expectTestsPass(await runCLIAsync(`test ${myapp} --no-watch`));
// TODO: remove this condition
if (getSelectedPackageManager() !== 'pnpm') {
expectTestsPass(await runCLIAsync(`test ${mylib} --no-watch`));
}
}, 1000000);
it('should work with creators using --module', async () => {
const myapp = uniq('myapp');
runCLI(
`generate @nx/angular:app ${myapp} --routing --no-standalone --project-name-and-root-format=as-provided --no-interactive`
);
// Generate root ngrx state management
runCLI(
`generate @nx/angular:ngrx users --parent=${myapp}/src/app/app.module.ts --root`
);
const packageJson = readJson('package.json');
expect(packageJson.dependencies['@ngrx/entity']).toBeDefined();
expect(packageJson.dependencies['@ngrx/store']).toBeDefined();
expect(packageJson.dependencies['@ngrx/effects']).toBeDefined();
expect(packageJson.dependencies['@ngrx/router-store']).toBeDefined();
expect(packageJson.devDependencies['@ngrx/schematics']).toBeDefined();
expect(packageJson.devDependencies['@ngrx/store-devtools']).toBeDefined();
const mylib = uniq('mylib');
// Generate feature library and ngrx state within that library
runCLI(
`g @nx/angular:lib ${mylib} --prefix=fl --no-standalone --project-name-and-root-format=as-provided`
);
const flags = `--facade --barrels`;
runCLI(
`generate @nx/angular:ngrx flights --module=${mylib}/src/lib/${mylib}.module.ts ${flags}`
);
expect(runCLI(`build ${myapp}`)).toMatch(/main-[a-zA-Z0-9]+\.js/);
expectTestsPass(await runCLIAsync(`test ${myapp} --no-watch`));
// TODO: remove this condition
if (getSelectedPackageManager() !== 'pnpm') {
expectTestsPass(await runCLIAsync(`test ${mylib} --no-watch`));
}
}, 1000000);
});
});
|
1,890 | 0 | petrpan-code/nrwl/nx/e2e/angular-extensions | petrpan-code/nrwl/nx/e2e/angular-extensions/src/tailwind.test.ts | import {
cleanupProject,
listFiles,
newProject,
readFile,
removeFile,
runCLI,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('Tailwind support', () => {
let project: string;
const defaultButtonBgColor = 'bg-blue-700';
const buildLibWithTailwind = {
name: uniq('build-lib-with-tailwind'),
buttonBgColor: 'bg-green-800',
};
const pubLibWithTailwind = {
name: uniq('pub-lib-with-tailwind'),
buttonBgColor: 'bg-red-900',
};
const spacing = {
root: {
sm: '2px',
md: '4px',
lg: '8px',
},
projectVariant1: {
sm: '1px',
md: '2px',
lg: '4px',
},
projectVariant2: {
sm: '4px',
md: '8px',
lg: '16px',
},
projectVariant3: {
sm: '8px',
md: '16px',
lg: '32px',
},
};
const createWorkspaceTailwindConfigFile = () => {
const tailwindConfigFile = 'tailwind.config.js';
const tailwindConfig = `module.exports = {
content: [
'**/!(*.stories|*.spec).{ts,html}',
'**/!(*.stories|*.spec).{ts,html}',
],
theme: {
spacing: {
sm: '${spacing.root.sm}',
md: '${spacing.root.md}',
lg: '${spacing.root.lg}',
},
},
plugins: [],
};
`;
updateFile(tailwindConfigFile, tailwindConfig);
};
const createTailwindConfigFile = (
tailwindConfigFile = 'tailwind.config.js',
libSpacing: typeof spacing['projectVariant1']
) => {
const tailwindConfig = `const { createGlobPatternsForDependencies } = require('@nx/angular/tailwind');
const { join } = require('path');
module.exports = {
content: [
join(__dirname, 'src/**/!(*.stories|*.spec).{ts,html}'),
...createGlobPatternsForDependencies(__dirname),
],
theme: {
spacing: {
sm: '${libSpacing.sm}',
md: '${libSpacing.md}',
lg: '${libSpacing.lg}',
},
},
plugins: [],
};
`;
updateFile(tailwindConfigFile, tailwindConfig);
};
const updateTailwindConfig = (
tailwindConfigPath: string,
projectSpacing: typeof spacing['root']
) => {
const tailwindConfig = readFile(tailwindConfigPath);
const tailwindConfigUpdated = tailwindConfig.replace(
'theme: {',
`theme: {
spacing: {
sm: '${projectSpacing.sm}',
md: '${projectSpacing.md}',
lg: '${projectSpacing.lg}',
},`
);
updateFile(tailwindConfigPath, tailwindConfigUpdated);
};
beforeAll(() => {
project = newProject();
// Create tailwind config in the workspace root
createWorkspaceTailwindConfigFile();
});
afterAll(() => {
cleanupProject();
});
describe('Libraries', () => {
const createLibComponent = (
lib: string,
buttonBgColor: string = defaultButtonBgColor
) => {
updateFile(
`${lib}/src/lib/foo.component.ts`,
`import { Component } from '@angular/core';
@Component({
selector: '${project}-foo',
template: '<button class="custom-btn text-white ${buttonBgColor}">Click me!</button>',
styles: [\`
.custom-btn {
@apply m-md p-sm;
}
\`]
})
export class FooComponent {}
`
);
updateFile(
`${lib}/src/lib/${lib}.module.ts`,
`import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FooComponent } from './foo.component';
@NgModule({
imports: [CommonModule],
declarations: [FooComponent],
exports: [FooComponent],
})
export class LibModule {}
`
);
updateFile(
`${lib}/src/index.ts`,
`export * from './lib/foo.component';
export * from './lib/${lib}.module';
`
);
};
const assertLibComponentStyles = (
lib: string,
libSpacing: typeof spacing['root']
) => {
const builtComponentContent = readFile(
`dist/${lib}/esm2022/lib/foo.component.mjs`
);
let expectedStylesRegex = new RegExp(
`styles: \\[\\"\\.custom\\-btn(\\[_ngcontent\\-%COMP%\\])?{margin:${libSpacing.md};padding:${libSpacing.sm}}(\\\\n)?\\"\\]`
);
expect(builtComponentContent).toMatch(expectedStylesRegex);
};
it('should generate a buildable library with tailwind and build correctly', () => {
runCLI(
`generate @nx/angular:lib ${buildLibWithTailwind.name} --buildable --add-tailwind --project-name-and-root-format=as-provided --no-interactive`
);
updateTailwindConfig(
`${buildLibWithTailwind.name}/tailwind.config.js`,
spacing.projectVariant1
);
createLibComponent(
buildLibWithTailwind.name,
buildLibWithTailwind.buttonBgColor
);
runCLI(`build ${buildLibWithTailwind.name}`);
assertLibComponentStyles(
buildLibWithTailwind.name,
spacing.projectVariant1
);
});
it('should set up tailwind in a previously generated buildable library and build correctly', () => {
const buildLibSetupTailwind = uniq('build-lib-setup-tailwind');
runCLI(
`generate @nx/angular:lib ${buildLibSetupTailwind} --buildable --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/angular:setup-tailwind ${buildLibSetupTailwind} --no-interactive`
);
updateTailwindConfig(
`${buildLibSetupTailwind}/tailwind.config.js`,
spacing.projectVariant2
);
createLibComponent(buildLibSetupTailwind);
runCLI(`build ${buildLibSetupTailwind}`);
assertLibComponentStyles(buildLibSetupTailwind, spacing.projectVariant2);
});
it('should correctly build a buildable library with a tailwind.config.js file in the project root or workspace root', () => {
const buildLibNoProjectConfig = uniq('build-lib-no-project-config');
runCLI(
`generate @nx/angular:lib ${buildLibNoProjectConfig} --buildable --project-name-and-root-format=as-provided --no-interactive`
);
createTailwindConfigFile(
`${buildLibNoProjectConfig}/tailwind.config.js`,
spacing.projectVariant3
);
createLibComponent(buildLibNoProjectConfig);
runCLI(`build ${buildLibNoProjectConfig}`);
assertLibComponentStyles(
buildLibNoProjectConfig,
spacing.projectVariant3
);
// remove tailwind.config.js file from the project root to test the one in the workspace root
removeFile(`${buildLibNoProjectConfig}/tailwind.config.js`);
runCLI(`build ${buildLibNoProjectConfig}`);
assertLibComponentStyles(buildLibNoProjectConfig, spacing.root);
});
it('should generate a publishable library with tailwind and build correctly', () => {
runCLI(
`generate @nx/angular:lib ${pubLibWithTailwind.name} --publishable --add-tailwind --importPath=@${project}/${pubLibWithTailwind.name} --project-name-and-root-format=as-provided --no-interactive`
);
updateTailwindConfig(
`${pubLibWithTailwind.name}/tailwind.config.js`,
spacing.projectVariant1
);
createLibComponent(
pubLibWithTailwind.name,
pubLibWithTailwind.buttonBgColor
);
runCLI(`build ${pubLibWithTailwind.name}`);
assertLibComponentStyles(
pubLibWithTailwind.name,
spacing.projectVariant1
);
});
it('should set up tailwind in a previously generated publishable library and build correctly', () => {
const pubLibSetupTailwind = uniq('pub-lib-setup-tailwind');
runCLI(
`generate @nx/angular:lib ${pubLibSetupTailwind} --publishable --importPath=@${project}/${pubLibSetupTailwind} --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/angular:setup-tailwind ${pubLibSetupTailwind} --no-interactive`
);
updateTailwindConfig(
`${pubLibSetupTailwind}/tailwind.config.js`,
spacing.projectVariant2
);
createLibComponent(pubLibSetupTailwind);
runCLI(`build ${pubLibSetupTailwind}`);
assertLibComponentStyles(pubLibSetupTailwind, spacing.projectVariant2);
});
it('should correctly build a publishable library with a tailwind.config.js file in the project root or workspace root', () => {
const pubLibNoProjectConfig = uniq('pub-lib-no-project-config');
runCLI(
`generate @nx/angular:lib ${pubLibNoProjectConfig} --publishable --importPath=@${project}/${pubLibNoProjectConfig} --project-name-and-root-format=as-provided --no-interactive`
);
createTailwindConfigFile(
`${pubLibNoProjectConfig}/tailwind.config.js`,
spacing.projectVariant3
);
createLibComponent(pubLibNoProjectConfig);
runCLI(`build ${pubLibNoProjectConfig}`);
assertLibComponentStyles(pubLibNoProjectConfig, spacing.projectVariant3);
// remove tailwind.config.js file from the project root to test the one in the workspace root
removeFile(`${pubLibNoProjectConfig}/tailwind.config.js`);
runCLI(`build ${pubLibNoProjectConfig}`);
assertLibComponentStyles(pubLibNoProjectConfig, spacing.root);
});
});
describe('Applications', () => {
const readAppStylesBundle = (outputPath: string) => {
const stylesBundlePath = listFiles(outputPath).find((file) =>
/^styles[\.-]/.test(file)
);
const stylesBundle = readFile(`${outputPath}/${stylesBundlePath}`);
return stylesBundle;
};
const assertAppComponentStyles = (
outputPath: string,
appSpacing: typeof spacing['root']
) => {
const mainBundlePath = listFiles(outputPath).find((file) =>
/^main[\.-]/.test(file)
);
const mainBundle = readFile(`${outputPath}/${mainBundlePath}`);
let expectedStylesRegex = new RegExp(
`styles:\\[\\"\\.custom\\-btn\\[_ngcontent\\-%COMP%\\]{margin:${appSpacing.md};padding:${appSpacing.sm}}\\"\\]`
);
expect(mainBundle).toMatch(expectedStylesRegex);
};
const setupTailwindAndProjectDependencies = (appName: string) => {
updateTailwindConfig(
`${appName}/tailwind.config.js`,
spacing.projectVariant1
);
updateFile(
`${appName}/src/app/app.module.ts`,
`import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LibModule as LibModule1 } from '@${project}/${buildLibWithTailwind.name}';
import { LibModule as LibModule2 } from '@${project}/${pubLibWithTailwind.name}';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, LibModule1, LibModule2],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
`
);
updateFile(
`${appName}/src/app/app.component.html`,
`<button class="custom-btn text-white">Click me!</button>`
);
updateFile(
`${appName}/src/app/app.component.css`,
`.custom-btn {
@apply m-md p-sm;
}`
);
};
it('should build correctly and only output the tailwind utilities used', async () => {
const appWithTailwind = uniq('app-with-tailwind');
runCLI(
`generate @nx/angular:app ${appWithTailwind} --add-tailwind --project-name-and-root-format=as-provided --no-interactive`
);
setupTailwindAndProjectDependencies(appWithTailwind);
runCLI(`build ${appWithTailwind}`);
const outputPath = `dist/${appWithTailwind}/browser`;
assertAppComponentStyles(outputPath, spacing.projectVariant1);
let stylesBundle = readAppStylesBundle(outputPath);
expect(stylesBundle).toContain('.text-white');
expect(stylesBundle).not.toContain('.text-black');
expect(stylesBundle).toContain(`.${buildLibWithTailwind.buttonBgColor}`);
expect(stylesBundle).toContain(`.${pubLibWithTailwind.buttonBgColor}`);
expect(stylesBundle).not.toContain(`.${defaultButtonBgColor}`);
});
it('should build correctly and only output the tailwind utilities used when using webpack and incremental builds', async () => {
const appWithTailwind = uniq('app-with-tailwind');
runCLI(
`generate @nx/angular:app ${appWithTailwind} --add-tailwind --bundler=webpack --project-name-and-root-format=as-provided --no-interactive`
);
setupTailwindAndProjectDependencies(appWithTailwind);
updateJson(join(appWithTailwind, 'project.json'), (config) => {
config.targets.build.executor = '@nx/angular:webpack-browser';
config.targets.build.options = {
...config.targets.build.options,
buildLibsFromSource: false,
};
return config;
});
runCLI(`build ${appWithTailwind}`);
const outputPath = `dist/${appWithTailwind}`;
assertAppComponentStyles(outputPath, spacing.projectVariant1);
let stylesBundle = readAppStylesBundle(outputPath);
expect(stylesBundle).toContain('.text-white');
expect(stylesBundle).not.toContain('.text-black');
expect(stylesBundle).toContain(`.${buildLibWithTailwind.buttonBgColor}`);
expect(stylesBundle).toContain(`.${pubLibWithTailwind.buttonBgColor}`);
expect(stylesBundle).not.toContain(`.${defaultButtonBgColor}`);
});
});
});
|
1,895 | 0 | petrpan-code/nrwl/nx/e2e/cypress | petrpan-code/nrwl/nx/e2e/cypress/src/cypress.test.ts | import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
createFile,
ensureCypressInstallation,
killPort,
newProject,
readJson,
runCLI,
runE2ETests,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
const TEN_MINS_MS = 600_000;
describe('Cypress E2E Test runner', () => {
const myapp = uniq('myapp');
beforeAll(() => {
newProject();
ensureCypressInstallation();
});
afterAll(() => cleanupProject());
it(
'should generate an app with the Cypress as e2e test runner',
() => {
runCLI(
`generate @nx/react:app ${myapp} --e2eTestRunner=cypress --linter=eslint`
);
// Making sure the package.json file contains the Cypress dependency
const packageJson = readJson('package.json');
expect(packageJson.devDependencies['cypress']).toBeTruthy();
// Making sure the cypress folders & files are created
checkFilesExist(`apps/${myapp}-e2e/cypress.config.ts`);
checkFilesExist(`apps/${myapp}-e2e/tsconfig.json`);
checkFilesExist(`apps/${myapp}-e2e/src/fixtures/example.json`);
checkFilesExist(`apps/${myapp}-e2e/src/e2e/app.cy.ts`);
checkFilesExist(`apps/${myapp}-e2e/src/support/app.po.ts`);
checkFilesExist(`apps/${myapp}-e2e/src/support/e2e.ts`);
checkFilesExist(`apps/${myapp}-e2e/src/support/commands.ts`);
},
TEN_MINS_MS
);
it(
'should execute e2e tests using Cypress',
async () => {
// make sure env vars work
createFile(
`apps/${myapp}-e2e/cypress.env.json`,
`
{
"cypressEnvJson": "i am from the cypress.env.json file"
}`
);
updateJson(`apps/${myapp}-e2e/project.json`, (json) => {
json.targets.e2e.options = {
...json.targets.e2e.options,
env: {
projectJson: 'i am from the nx project json file',
},
};
return json;
});
createFile(
`apps/${myapp}-e2e/src/e2e/env.cy.ts`,
`
describe('env vars', () => {
it('should have cli args', () => {
assert.equal(Cypress.env('cliArg'), 'i am from the cli args');
});
it('should have cypress.env.json vars', () => {
assert.equal(
Cypress.env('cypressEnvJson'),
'i am from the cypress.env.json file'
);
});
it('cli args should not merged project.json vars', () => {
assert.equal(
Cypress.env('projectJson'),
undefined
);
});
});`
);
if (runE2ETests()) {
// contains the correct output and works
const run1 = runCLI(
`e2e ${myapp}-e2e --no-watch --env.cliArg="i am from the cli args"`
);
expect(run1).toContain('All specs passed!');
await killPort(4200);
// tests should not fail because of a config change
updateFile(
`apps/${myapp}-e2e/cypress.config.ts`,
`
import { defineConfig } from 'cypress';
import { nxE2EPreset } from '@nx/cypress/plugins/cypress-preset';
export default defineConfig({
e2e: {
...nxE2EPreset(__dirname),
fixturesFolder: undefined,
},
});`
);
const run2 = runCLI(
`e2e ${myapp}-e2e --no-watch --env.cliArg="i am from the cli args"`
);
expect(run2).toContain('All specs passed!');
await killPort(4200);
// make sure project.json env vars also work
updateFile(
`apps/${myapp}-e2e/src/e2e/env.cy.ts`,
`
describe('env vars', () => {
it('should not have cli args', () => {
assert.equal(Cypress.env('cliArg'), undefined);
});
it('should have cypress.env.json vars', () => {
assert.equal(
Cypress.env('cypressEnvJson'),
'i am from the cypress.env.json file'
);
});
it('should have project.json vars', () => {
assert.equal(
Cypress.env('projectJson'),
'i am from the nx project json file'
);
});
});`
);
const run3 = runCLI(`e2e ${myapp}-e2e --no-watch`);
expect(run3).toContain('All specs passed!');
expect(await killPort(4200)).toBeTruthy();
}
},
TEN_MINS_MS
);
it(
'should run e2e in parallel',
async () => {
const ngAppName = uniq('ng-app');
runCLI(
`generate @nx/angular:app ${ngAppName} --e2eTestRunner=cypress --linter=eslint --no-interactive`
);
if (runE2ETests()) {
const results = runCLI(
`run-many --target=e2e --parallel=2 --port=cypress-auto --output-style=stream`
);
expect(results).toContain('Successfully ran target e2e for 2 projects');
}
},
TEN_MINS_MS
);
it.each(['react', 'next', 'angular'])(
`should allow CT and e2e in same project - %s`,
async (framework: 'react' | 'next' | 'angular') => {
await testCtAndE2eInProject(framework);
},
TEN_MINS_MS
);
});
async function testCtAndE2eInProject(
projectType: 'react' | 'next' | 'angular'
) {
let appName = uniq(`${projectType}-cy-app`);
runCLI(
`generate @nx/${projectType}:app ${appName} --e2eTestRunner=none --no-interactive ${
projectType === 'angular' ? '--bundler=webpack' : ''
}`
);
runCLI(
`generate @nx/${projectType}:component btn --project=${appName} --no-interactive`
);
runCLI(
`generate @nx/${projectType}:cypress-component-configuration --project=${appName} --generate-tests --no-interactive`
);
if (runE2ETests()) {
expect(runCLI(`run ${appName}:component-test --no-watch`)).toContain(
'All specs passed!'
);
}
runCLI(`generate @nx/cypress:e2e --project=${appName} --no-interactive`);
if (runE2ETests()) {
expect(runCLI(`run ${appName}:e2e --no-watch`)).toContain(
'All specs passed!'
);
}
expect(await killPort(4200)).toBeTruthy();
}
|
1,900 | 0 | petrpan-code/nrwl/nx/e2e/detox | petrpan-code/nrwl/nx/e2e/detox/src/detox.test.ts | import {
checkFilesExist,
isOSX,
newProject,
runCLI,
runCLIAsync,
uniq,
killPorts,
cleanupProject,
} from '@nx/e2e/utils';
describe('Detox', () => {
const appName = uniq('myapp');
beforeAll(() => {
newProject();
});
afterAll(() => cleanupProject());
it('should create files and run lint command for react-native apps', async () => {
runCLI(
`generate @nx/react-native:app ${appName} --e2eTestRunner=detox --linter=eslint --install=false`
);
checkFilesExist(`apps/${appName}-e2e/.detoxrc.json`);
checkFilesExist(`apps/${appName}-e2e/tsconfig.json`);
checkFilesExist(`apps/${appName}-e2e/tsconfig.e2e.json`);
checkFilesExist(`apps/${appName}-e2e/test-setup.ts`);
checkFilesExist(`apps/${appName}-e2e/src/app.spec.ts`);
const lintResults = await runCLIAsync(`lint ${appName}-e2e`);
expect(lintResults.combinedOutput).toContain('All files pass linting');
});
it('should create files and run lint command for expo apps', async () => {
const expoAppName = uniq('myapp');
runCLI(
`generate @nx/expo:app ${expoAppName} --e2eTestRunner=detox --linter=eslint`
);
checkFilesExist(`apps/${expoAppName}-e2e/.detoxrc.json`);
checkFilesExist(`apps/${expoAppName}-e2e/tsconfig.json`);
checkFilesExist(`apps/${expoAppName}-e2e/tsconfig.e2e.json`);
checkFilesExist(`apps/${expoAppName}-e2e/test-setup.ts`);
checkFilesExist(`apps/${expoAppName}-e2e/src/app.spec.ts`);
const lintResults = await runCLIAsync(`lint ${expoAppName}-e2e`);
expect(lintResults.combinedOutput).toContain('All files pass linting');
});
it('should support generating projects with the new name and root format', async () => {
const appName = uniq('app1');
runCLI(
`generate @nx/react-native:app ${appName} --e2eTestRunner=detox --linter=eslint --install=false --project-name-and-root-format=as-provided`
);
// check files are generated without the layout directory ("apps/") and
// using the project name as the directory when no directory is provided
checkFilesExist(
`${appName}-e2e/.detoxrc.json`,
`${appName}-e2e/tsconfig.json`,
`${appName}-e2e/tsconfig.e2e.json`,
`${appName}-e2e/test-setup.ts`,
`${appName}-e2e/src/app.spec.ts`
);
const lintResults = await runCLIAsync(`lint ${appName}-e2e`);
expect(lintResults.combinedOutput).toContain('All files pass linting');
});
// TODO: @xiongemi please fix or remove this test
xdescribe('React Native Detox MACOS-Tests', () => {
if (isOSX()) {
it('should test ios MACOS-Tests', async () => {
expect(
runCLI(
`test-ios ${appName}-e2e --prod --debugSynchronization=true --loglevel=trace`
)
).toContain('Successfully ran target test-ios');
await killPorts(8081); // kill the port for the serve command
}, 3000000);
}
});
});
|
1,905 | 0 | petrpan-code/nrwl/nx/e2e/esbuild | petrpan-code/nrwl/nx/e2e/esbuild/src/esbuild.test.ts | import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
detectPackageManager,
newProject,
packageInstall,
packageManagerLockFile,
readFile,
readJson,
runCLI,
runCommand,
runCommandUntil,
tmpProjPath,
uniq,
updateFile,
updateJson,
waitUntil,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('EsBuild Plugin', () => {
let proj: string;
beforeEach(() => (proj = newProject()));
afterEach(() => cleanupProject());
it('should setup and build projects using build', async () => {
const myPkg = uniq('my-pkg');
runCLI(`generate @nx/js:lib ${myPkg} --bundler=esbuild`);
updateFile(`libs/${myPkg}/src/index.ts`, `console.log('Hello');\n`);
updateJson(join('libs', myPkg, 'project.json'), (json) => {
json.targets.build.options.assets = [`libs/${myPkg}/assets/*`];
return json;
});
updateFile(`libs/${myPkg}/assets/a.md`, 'file a');
updateFile(`libs/${myPkg}/assets/b.md`, 'file b');
// Copy package.json as asset rather than generate with Nx-detected fields.
runCLI(`build ${myPkg} --generatePackageJson=false`);
const packageJson = readJson(`libs/${myPkg}/package.json`);
// This is the file that is generated by lib generator (no deps, no main, etc.).
expect(packageJson).toEqual({
name: `@proj/${myPkg}`,
version: '0.0.1',
type: 'commonjs',
main: './index.cjs',
dependencies: {},
});
// Build normally with package.json generation.
runCLI(`build ${myPkg}`);
expect(runCommand(`node dist/libs/${myPkg}/index.cjs`)).toMatch(/Hello/);
// main field should be set correctly in package.json
checkFilesExist(
`dist/libs/${myPkg}/package.json`,
`dist/libs/${myPkg}/${
packageManagerLockFile[detectPackageManager(tmpProjPath())]
}`
);
expect(runCommand(`node dist/libs/${myPkg}`)).toMatch(/Hello/);
expect(runCommand(`node dist/libs/${myPkg}/index.cjs`)).toMatch(/Hello/);
// main field should be set correctly in package.json
expect(readFile(`dist/libs/${myPkg}/assets/a.md`)).toMatch(/file a/);
expect(readFile(`dist/libs/${myPkg}/assets/b.md`)).toMatch(/file b/);
/* Metafile is not generated by default, but passing --metafile generates it.
*/
checkFilesDoNotExist(`dist/libs/${myPkg}/meta.json`);
runCLI(`build ${myPkg} --metafile`);
checkFilesExist(`dist/libs/${myPkg}/meta.json`);
/* Type errors are turned on by default
*/
updateFile(
`libs/${myPkg}/src/index.ts`,
`
const x: number = 'a'; // type error
console.log('Bye');
`
);
expect(() => runCLI(`build ${myPkg}`)).toThrow();
expect(() => runCLI(`build ${myPkg} --skipTypeCheck`)).not.toThrow();
expect(runCommand(`node dist/libs/${myPkg}/index.cjs`)).toMatch(/Bye/);
// Reset file
updateFile(
`libs/${myPkg}/src/index.ts`,
`
console.log('Hello');
`
);
// TODO: Investigate why these assertions are flaky in CI
/* Test that watch mode copies assets on start, and again on update.
*/
// updateFile(`libs/${myPkg}/assets/a.md`, 'initial a');
// const watchProcess = await runCommandUntil(
// `build ${myPkg} --watch`,
// (output) => {
// return output.includes('watching for changes');
// }
// );
// readFile(`dist/libs/${myPkg}/assets/a.md`).includes('initial a');
// updateFile(`libs/${myPkg}/assets/a.md`, 'updated a');
// await expect(
// waitUntil(
// () => readFile(`dist/libs/${myPkg}/assets/a.md`).includes('updated a'),
// {
// timeout: 20_000,
// ms: 500,
// }
// )
// ).resolves.not.toThrow();
// watchProcess.kill();
}, 300_000);
it('should support bundling everything or only workspace libs', async () => {
packageInstall('rambda', undefined, '~7.3.0', 'prod');
packageInstall('lodash', undefined, '~4.14.0', 'prod');
const parentLib = uniq('parent-lib');
const childLib = uniq('child-lib');
runCLI(`generate @nx/js:lib ${parentLib} --bundler=esbuild`);
runCLI(`generate @nx/js:lib ${childLib} --bundler=none`);
updateFile(
`libs/${parentLib}/src/index.ts`,
`
// @ts-ignore
import _ from 'lodash';
import { greet } from '@${proj}/${childLib}';
console.log(_.upperFirst('hello world'));
console.log(greet());
`
);
updateFile(
`libs/${childLib}/src/index.ts`,
`
import { always } from 'rambda';
export const greet = always('Hello from child lib');
`
);
// Bundle child lib and third-party packages
runCLI(`build ${parentLib}`);
expect(
readJson(`dist/libs/${parentLib}/package.json`).dependencies?.['dayjs']
).not.toBeDefined();
let runResult = runCommand(`node dist/libs/${parentLib}/index.cjs`);
expect(runResult).toMatch(/Hello world/);
expect(runResult).toMatch(/Hello from child lib/);
// Bundle only child lib
runCLI(`build ${parentLib} --third-party=false`);
expect(
readJson(`dist/libs/${parentLib}/package.json`).dependencies
).toEqual({
// Don't care about the versions, just that they exist
rambda: expect.any(String),
lodash: expect.any(String),
});
runResult = runCommand(`node dist/libs/${parentLib}/index.cjs`);
expect(runResult).toMatch(/Hello world/);
expect(runResult).toMatch(/Hello from child lib/);
}, 300_000);
it('should support non-bundle builds', () => {
const myPkg = uniq('my-pkg');
runCLI(`generate @nx/js:lib ${myPkg} --bundler=esbuild`);
updateFile(`libs/${myPkg}/src/lib/${myPkg}.ts`, `console.log('Hello');\n`);
updateFile(`libs/${myPkg}/src/index.ts`, `import './lib/${myPkg}.cjs';\n`);
runCLI(`build ${myPkg} --bundle=false`);
checkFilesExist(
`dist/libs/${myPkg}/libs/${myPkg}/src/lib/${myPkg}.cjs`,
`dist/libs/${myPkg}/index.cjs`
);
// Test files are excluded in tsconfig (e.g. tsconfig.lib.json)
checkFilesDoNotExist(
`dist/libs/${myPkg}/libs/${myPkg}/src/lib/${myPkg}.spec.cjs`
);
// Can run package (package.json fields are correctly generated)
expect(runCommand(`node dist/libs/${myPkg}`)).toMatch(/Hello/);
}, 300_000);
it('should support additional entry points', async () => {
const myPkg = uniq('my-pkg');
runCLI(`generate @nx/js:lib ${myPkg} --bundler=esbuild`);
updateFile(`libs/${myPkg}/src/index.ts`, `console.log('main');\n`);
updateFile(`libs/${myPkg}/src/extra.ts`, `console.log('extra');\n`);
updateJson(join('libs', myPkg, 'project.json'), (json) => {
json.targets.build.options.additionalEntryPoints = [
`libs/${myPkg}/src/extra.ts`,
];
return json;
});
runCLI(`build ${myPkg}`);
checkFilesExist(
`dist/libs/${myPkg}/index.cjs`,
`dist/libs/${myPkg}/extra.cjs`
);
expect(
runCommand(`node dist/libs/${myPkg}/index.cjs`, { failOnError: true })
).toMatch(/main/);
expect(
runCommand(`node dist/libs/${myPkg}/extra.cjs`, { failOnError: true })
).toMatch(/extra/);
}, 120_000);
it('should support external esbuild.config.js file', async () => {
const myPkg = uniq('my-pkg');
runCLI(`generate @nx/js:lib ${myPkg} --bundler=esbuild`);
updateFile(
`libs/${myPkg}/esbuild.config.js`,
`console.log('custom config loaded');\nmodule.exports = {};\n`
);
updateJson(join('libs', myPkg, 'project.json'), (json) => {
delete json.targets.build.options.esbuildOptions;
json.targets.build.options.esbuildConfig = `libs/${myPkg}/esbuild.config.js`;
return json;
});
const output = runCLI(`build ${myPkg}`);
expect(output).toContain('custom config loaded');
}, 120_000);
});
|
1,910 | 0 | petrpan-code/nrwl/nx/e2e/eslint | petrpan-code/nrwl/nx/e2e/eslint/src/linter.test.ts | import * as path from 'path';
import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
createFile,
getSelectedPackageManager,
newProject,
readFile,
readJson,
renameFile,
runCLI,
runCreateWorkspace,
setMaxWorkers,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import * as ts from 'typescript';
describe('Linter', () => {
describe('Integrated', () => {
const myapp = uniq('myapp');
const mylib = uniq('mylib');
let projScope;
beforeAll(() => {
projScope = newProject();
runCLI(`generate @nx/react:app ${myapp} --tags=validtag`);
runCLI(`generate @nx/js:lib ${mylib}`);
});
afterAll(() => cleanupProject());
describe('linting errors', () => {
let defaultEslintrc;
beforeAll(() => {
updateFile(`apps/${myapp}/src/main.ts`, `console.log("should fail");`);
defaultEslintrc = readJson('.eslintrc.json');
});
afterEach(() => {
updateFile('.eslintrc.json', JSON.stringify(defaultEslintrc, null, 2));
});
it('should check for linting errors', () => {
// create faulty file
updateFile(`apps/${myapp}/src/main.ts`, `console.log("should fail");`);
const eslintrc = readJson('.eslintrc.json');
// set the eslint rules to error
eslintrc.overrides.forEach((override) => {
if (override.files.includes('*.ts')) {
override.rules['no-console'] = 'error';
}
});
updateFile('.eslintrc.json', JSON.stringify(eslintrc, null, 2));
// 1. linting should error when rules are not followed
let out = runCLI(`lint ${myapp}`, { silenceError: true });
expect(out).toContain('Unexpected console statement');
// 2. linting should not error when rules are not followed and the force flag is specified
expect(() => runCLI(`lint ${myapp} --force`)).not.toThrow();
eslintrc.overrides.forEach((override) => {
if (override.files.includes('*.ts')) {
override.rules['no-console'] = undefined;
}
});
updateFile('.eslintrc.json', JSON.stringify(eslintrc, null, 2));
// 3. linting should not error when all rules are followed
out = runCLI(`lint ${myapp}`, { silenceError: true });
expect(out).toContain('All files pass linting');
}, 1000000);
it('should cache eslint with --cache', () => {
function readCacheFile(cacheFile) {
const cacheInfo = readFile(cacheFile);
return process.platform === 'win32'
? cacheInfo.replace(/\\\\/g, '\\')
: cacheInfo;
}
// should generate a default cache file
expect(() => checkFilesExist(`.eslintcache`)).toThrow();
runCLI(`lint ${myapp} --cache`, { silenceError: true });
expect(() => checkFilesExist(`.eslintcache`)).not.toThrow();
expect(readCacheFile(`.eslintcache`)).toContain(
path.normalize(`${myapp}/src/app/app.spec.tsx`)
);
// should let you specify a cache file location
expect(() => checkFilesExist(`my-cache`)).toThrow();
runCLI(`lint ${myapp} --cache --cache-location="my-cache"`, {
silenceError: true,
});
expect(() => checkFilesExist(`my-cache/${myapp}`)).not.toThrow();
expect(readCacheFile(`my-cache/${myapp}`)).toContain(
path.normalize(`${myapp}/src/app/app.spec.tsx`)
);
});
it('linting should generate an output file with a specific format', () => {
const eslintrc = readJson('.eslintrc.json');
eslintrc.overrides.forEach((override) => {
if (override.files.includes('*.ts')) {
override.rules['no-console'] = 'error';
}
});
updateFile('.eslintrc.json', JSON.stringify(eslintrc, null, 2));
const outputFile = 'a/b/c/lint-output.json';
expect(() => {
checkFilesExist(outputFile);
}).toThrow();
const stdout = runCLI(
`lint ${myapp} --output-file="${outputFile}" --format=json`,
{
silenceError: true,
}
);
expect(stdout).not.toContain('Unexpected console statement');
expect(() => checkFilesExist(outputFile)).not.toThrow();
const outputContents = JSON.parse(readFile(outputFile));
const outputForApp: any = Object.values(outputContents).filter(
(result: any) =>
result.filePath.includes(path.normalize(`${myapp}/src/main.ts`))
)[0];
expect(outputForApp.errorCount).toBe(1);
expect(outputForApp.messages[0].ruleId).toBe('no-console');
expect(outputForApp.messages[0].message).toBe(
'Unexpected console statement.'
);
}, 1000000);
it('should support creating, testing and using workspace lint rules', () => {
const messageId = 'e2eMessageId';
const libMethodName = 'getMessageId';
// add custom function
updateFile(
`libs/${mylib}/src/lib/${mylib}.ts`,
`export const ${libMethodName} = (): '${messageId}' => '${messageId}';`
);
// Generate a new rule (should also scaffold the required workspace project and tests)
const newRuleName = 'e2e-test-rule-name';
runCLI(`generate @nx/eslint:workspace-rule ${newRuleName}`);
// Ensure that the unit tests for the new rule are runnable
const unitTestsOutput = runCLI(`test eslint-rules`);
expect(unitTestsOutput).toContain('Successfully ran target test');
// Update the rule for the e2e test so that we can assert that it produces the expected lint failure when used
const knownLintErrorMessage = 'e2e test known error message';
const newRulePath = `tools/eslint-rules/rules/${newRuleName}.ts`;
const newRuleGeneratedContents = readFile(newRulePath);
const updatedRuleContents = updateGeneratedRuleImplementation(
newRulePath,
newRuleGeneratedContents,
knownLintErrorMessage,
messageId,
libMethodName,
`@${projScope}/${mylib}`
);
updateFile(newRulePath, updatedRuleContents);
const newRuleNameForUsage = `@nx/workspace/${newRuleName}`;
// Add the new workspace rule to the lint config and run linting
const eslintrc = readJson('.eslintrc.json');
eslintrc.overrides.forEach((override) => {
if (override.files.includes('*.ts')) {
override.rules[newRuleNameForUsage] = 'error';
}
});
updateFile('.eslintrc.json', JSON.stringify(eslintrc, null, 2));
const lintOutput = runCLI(`lint ${myapp} --verbose`, {
silenceError: true,
});
expect(lintOutput).toContain(newRuleNameForUsage);
expect(lintOutput).toContain(knownLintErrorMessage);
}, 1000000);
it('lint plugin should ensure module boundaries', () => {
const myapp2 = uniq('myapp2');
const lazylib = uniq('lazylib');
const invalidtaglib = uniq('invalidtaglib');
const validtaglib = uniq('validtaglib');
runCLI(`generate @nx/react:app ${myapp2}`);
runCLI(`generate @nx/react:lib ${lazylib}`);
runCLI(`generate @nx/js:lib ${invalidtaglib} --tags=invalidtag`);
runCLI(`generate @nx/js:lib ${validtaglib} --tags=validtag`);
const eslint = readJson('.eslintrc.json');
eslint.overrides[0].rules[
'@nx/enforce-module-boundaries'
][1].depConstraints = [
{ sourceTag: 'validtag', onlyDependOnLibsWithTags: ['validtag'] },
...eslint.overrides[0].rules['@nx/enforce-module-boundaries'][1]
.depConstraints,
];
updateFile('.eslintrc.json', JSON.stringify(eslint, null, 2));
const tsConfig = readJson('tsconfig.base.json');
/**
* apps do not add themselves to the tsconfig file.
*
* Let's add it so that we can trigger the lint failure
*/
tsConfig.compilerOptions.paths[`@${projScope}/${myapp2}`] = [
`apps/${myapp2}/src/main.ts`,
];
tsConfig.compilerOptions.paths[`@secondScope/${lazylib}`] =
tsConfig.compilerOptions.paths[`@${projScope}/${lazylib}`];
delete tsConfig.compilerOptions.paths[`@${projScope}/${lazylib}`];
updateFile('tsconfig.base.json', JSON.stringify(tsConfig, null, 2));
updateFile(
`apps/${myapp}/src/main.ts`,
`
import '../../../libs/${mylib}';
import '@secondScope/${lazylib}';
import '@${projScope}/${myapp2}';
import '@${projScope}/${invalidtaglib}';
import '@${projScope}/${validtaglib}';
const s = {loadChildren: '@secondScope/${lazylib}'};
`
);
const out = runCLI(`lint ${myapp}`, { silenceError: true });
expect(out).toContain(
'Projects cannot be imported by a relative or absolute path, and must begin with a npm scope'
);
expect(out).toContain('Imports of apps are forbidden');
expect(out).toContain(
'A project tagged with "validtag" can only depend on libs tagged with "validtag"'
);
}, 1000000);
it('should print the effective configuration for a file specified using --printConfig', () => {
const eslint = readJson('.eslintrc.json');
eslint.overrides.push({
files: ['src/index.ts'],
rules: {
'specific-rule': 'off',
},
});
updateFile('.eslintrc.json', JSON.stringify(eslint, null, 2));
const out = runCLI(`lint ${myapp} --printConfig src/index.ts`, {
silenceError: true,
});
expect(out).toContain('"specific-rule": [');
}, 1000000);
});
describe('workspace boundary rules', () => {
const libA = uniq('tslib-a');
const libB = uniq('tslib-b');
const libC = uniq('tslib-c');
beforeAll(() => {
runCLI(`generate @nx/js:lib ${libA}`);
runCLI(`generate @nx/js:lib ${libB}`);
runCLI(`generate @nx/js:lib ${libC}`);
/**
* create tslib-a structure
*/
createFile(
`libs/${libA}/src/lib/tslib-a.ts`,
`
export function libASayHi(): string {
return 'hi there';
}
export function libASayHello(): string {
return 'Hi from tslib-a';
}
`
);
createFile(
`libs/${libA}/src/lib/some-non-exported-function.ts`,
`
export function someNonPublicLibFunction() {
return 'this function is exported, but not via the libs barrel file';
}
export function someSelectivelyExportedFn() {
return 'this fn is exported selectively in the barrel file';
}
`
);
createFile(
`libs/${libA}/src/index.ts`,
`
export * from './lib/tslib-a';
export { someSelectivelyExportedFn } from './lib/some-non-exported-function';
`
);
/**
* create tslib-b structure
*/
createFile(
`libs/${libB}/src/index.ts`,
`
export * from './lib/tslib-b';
`
);
createFile(
`libs/${libB}/src/lib/tslib-b.ts`,
`
import { libASayHi } from 'libs/${libA}/src/lib/tslib-a';
import { libASayHello } from '../../../${libA}/src/lib/tslib-a';
// import { someNonPublicLibFunction } from '../../../${libA}/src/lib/some-non-exported-function';
import { someSelectivelyExportedFn } from '../../../${libA}/src/lib/some-non-exported-function';
export function tslibB(): string {
// someNonPublicLibFunction();
someSelectivelyExportedFn();
libASayHi();
libASayHello();
return 'hi there';
}
`
);
/**
* create tslib-c structure
*/
createFile(
`libs/${libC}/src/index.ts`,
`
export * from './lib/tslib-c';
export * from './lib/constant';
`
);
createFile(
`libs/${libC}/src/lib/constant.ts`,
`
export const SOME_CONSTANT = 'some constant value';
export const someFunc1 = () => 'hi';
export function someFunc2() {
return 'hi2';
}
`
);
createFile(
`libs/${libC}/src/lib/tslib-c-another.ts`,
`
import { tslibC, SOME_CONSTANT, someFunc1, someFunc2 } from '@${projScope}/${libC}';
export function someStuff() {
someFunc1();
someFunc2();
tslibC();
console.log(SOME_CONSTANT);
return 'hi';
}
`
);
createFile(
`libs/${libC}/src/lib/tslib-c.ts`,
`
import { someFunc1, someFunc2, SOME_CONSTANT } from '@${projScope}/${libC}';
export function tslibC(): string {
someFunc1();
someFunc2();
console.log(SOME_CONSTANT);
return 'tslib-c';
}
`
);
});
it('should fix noSelfCircularDependencies', () => {
const stdout = runCLI(`lint ${libC}`, {
silenceError: true,
});
expect(stdout).toContain(
'Projects should use relative imports to import from other files within the same project'
);
// fix them
const fixedStout = runCLI(`lint ${libC} --fix`, {
silenceError: true,
});
expect(fixedStout).toContain(
`Successfully ran target lint for project ${libC}`
);
const fileContent = readFile(`libs/${libC}/src/lib/tslib-c-another.ts`);
expect(fileContent).toContain(`import { tslibC } from './tslib-c';`);
expect(fileContent).toContain(
`import { SOME_CONSTANT, someFunc1, someFunc2 } from './constant';`
);
const fileContentTslibC = readFile(`libs/${libC}/src/lib/tslib-c.ts`);
expect(fileContentTslibC).toContain(
`import { someFunc1, someFunc2, SOME_CONSTANT } from './constant';`
);
});
it('should fix noRelativeOrAbsoluteImportsAcrossLibraries', () => {
const stdout = runCLI(`lint ${libB}`, {
silenceError: true,
});
expect(stdout).toContain(
'Projects cannot be imported by a relative or absolute path, and must begin with a npm scope'
);
// fix them
const fixedStout = runCLI(`lint ${libB} --fix`, {
silenceError: true,
});
expect(fixedStout).toContain(
`Successfully ran target lint for project ${libB}`
);
const fileContent = readFile(`libs/${libB}/src/lib/tslib-b.ts`);
expect(fileContent).toContain(
`import { libASayHello } from '@${projScope}/${libA}';`
);
expect(fileContent).toContain(
`import { libASayHi } from '@${projScope}/${libA}';`
);
expect(fileContent).toContain(
`import { someSelectivelyExportedFn } from '@${projScope}/${libA}';`
);
});
});
describe('dependency checks', () => {
beforeAll(() => {
updateJson(`libs/${mylib}/.eslintrc.json`, (json) => {
json.overrides = [
...json.overrides,
{
files: ['*.json'],
parser: 'jsonc-eslint-parser',
rules: {
'@nx/dependency-checks': 'error',
},
},
];
return json;
});
updateJson(`libs/${mylib}/project.json`, (json) => {
json.targets.lint.options.lintFilePatterns = [
`libs/${mylib}/**/*.ts`,
`libs/${mylib}/project.json`,
`libs/${mylib}/package.json`,
];
return json;
});
});
it('should report dependency check issues', () => {
const rootPackageJson = readJson('package.json');
const nxVersion = rootPackageJson.devDependencies.nx;
const tslibVersion = rootPackageJson.dependencies['tslib'];
let out = runCLI(`lint ${mylib}`, { silenceError: true });
expect(out).toContain('All files pass linting');
// make an explict dependency to nx
updateFile(
`libs/${mylib}/src/lib/${mylib}.ts`,
(content) =>
`import { names } from '@nx/devkit';\n\n` +
content.replace(/=> .*;/, `=> names(${mylib}).className;`)
);
// output should now report missing dependency
out = runCLI(`lint ${mylib}`, { silenceError: true });
expect(out).toContain('they are missing');
expect(out).toContain('@nx/devkit');
// should fix the missing dependency issue
out = runCLI(`lint ${mylib} --fix`, { silenceError: true });
expect(out).toContain(
`Successfully ran target lint for project ${mylib}`
);
const packageJson = readJson(`libs/${mylib}/package.json`);
expect(packageJson).toMatchInlineSnapshot(`
{
"dependencies": {
"@nx/devkit": "${nxVersion}",
"tslib": "${tslibVersion}",
},
"main": "./src/index.js",
"name": "@proj/${mylib}",
"type": "commonjs",
"typings": "./src/index.d.ts",
"version": "0.0.1",
}
`);
// intentionally set the invalid version
updateJson(`libs/${mylib}/package.json`, (json) => {
json.dependencies['@nx/devkit'] = '100.0.0';
return json;
});
out = runCLI(`lint ${mylib}`, { silenceError: true });
expect(out).toContain(
'version specifier does not contain the installed version of "@nx/devkit"'
);
// should fix the version mismatch issue
out = runCLI(`lint ${mylib} --fix`, { silenceError: true });
expect(out).toContain(
`Successfully ran target lint for project ${mylib}`
);
});
});
});
describe('Flat config', () => {
const packageManager = getSelectedPackageManager() || 'pnpm';
afterEach(() => cleanupProject());
it('should convert integrated to flat config', () => {
const myapp = uniq('myapp');
const mylib = uniq('mylib');
const mylib2 = uniq('mylib2');
runCreateWorkspace(myapp, {
preset: 'react-monorepo',
appName: myapp,
style: 'css',
packageManager,
bundler: 'vite',
e2eTestRunner: 'none',
});
runCLI(
`generate @nx/js:lib ${mylib} --directory libs/${mylib} --projectNameAndRootFormat as-provided`
);
runCLI(
`generate @nx/js:lib ${mylib2} --directory libs/${mylib2} --projectNameAndRootFormat as-provided`
);
// migrate to flat structure
runCLI(`generate @nx/eslint:convert-to-flat-config`);
checkFilesExist(
'eslint.config.js',
`apps/${myapp}/eslint.config.js`,
`libs/${mylib}/eslint.config.js`,
`libs/${mylib2}/eslint.config.js`
);
checkFilesDoNotExist(
'.eslintrc.json',
`apps/${myapp}/.eslintrc.json`,
`libs/${mylib}/.eslintrc.json`,
`libs/${mylib2}/.eslintrc.json`
);
// move eslint.config one step up
// to test the absence of the flat eslint config in the project root folder
renameFile(`libs/${mylib2}/eslint.config.js`, `libs/eslint.config.js`);
updateFile(
`libs/eslint.config.js`,
readFile(`libs/eslint.config.js`).replace(
`../../eslint.config.js`,
`../eslint.config.js`
)
);
const outFlat = runCLI(`affected -t lint`, {
silenceError: true,
});
expect(outFlat).toContain('All files pass linting');
}, 1000000);
it('should convert standalone to flat config', () => {
const myapp = uniq('myapp');
const mylib = uniq('mylib');
runCreateWorkspace(myapp, {
preset: 'react-standalone',
appName: myapp,
style: 'css',
packageManager,
bundler: 'vite',
e2eTestRunner: 'none',
});
runCLI(`generate @nx/js:lib ${mylib}`);
// migrate to flat structure
runCLI(`generate @nx/eslint:convert-to-flat-config`);
checkFilesExist(
'eslint.config.js',
`${mylib}/eslint.config.js`,
'eslint.base.config.js'
);
checkFilesDoNotExist(
'.eslintrc.json',
`${mylib}/.eslintrc.json`,
'.eslintrc.base.json'
);
const outFlat = runCLI(`affected -t lint`, {
silenceError: true,
});
expect(outFlat).toContain('All files pass linting');
}, 1000000);
});
describe('Root projects migration', () => {
beforeEach(() => newProject());
afterEach(() => cleanupProject());
function verifySuccessfulStandaloneSetup(myapp: string) {
expect(runCLI(`lint ${myapp}`, { silenceError: true })).toContain(
'All files pass linting'
);
expect(runCLI(`lint e2e`, { silenceError: true })).toContain(
'All files pass linting'
);
expect(() => checkFilesExist(`.eslintrc.base.json`)).toThrow();
const rootEslint = readJson('.eslintrc.json');
const e2eEslint = readJson('e2e/.eslintrc.json');
// should directly refer to nx plugin
expect(rootEslint.plugins).toEqual(['@nx']);
expect(e2eEslint.plugins).toEqual(['@nx']);
}
function verifySuccessfulMigratedSetup(myapp: string, mylib: string) {
expect(runCLI(`lint ${myapp}`, { silenceError: true })).toContain(
'All files pass linting'
);
expect(runCLI(`lint e2e`, { silenceError: true })).toContain(
'All files pass linting'
);
expect(runCLI(`lint ${mylib}`, { silenceError: true })).toContain(
'All files pass linting'
);
expect(() => checkFilesExist(`.eslintrc.base.json`)).not.toThrow();
const rootEslint = readJson('.eslintrc.base.json');
const appEslint = readJson('.eslintrc.json');
const e2eEslint = readJson('e2e/.eslintrc.json');
const libEslint = readJson(`libs/${mylib}/.eslintrc.json`);
// should directly refer to nx plugin
expect(rootEslint.plugins).toEqual(['@nx']);
expect(appEslint.plugins).toBeUndefined();
expect(e2eEslint.plugins).toBeUndefined();
expect(libEslint.plugins).toBeUndefined();
// should extend base
expect(appEslint.extends.slice(-1)).toEqual(['./.eslintrc.base.json']);
expect(e2eEslint.extends.slice(-1)).toEqual(['../.eslintrc.base.json']);
expect(libEslint.extends.slice(-1)).toEqual([
'../../.eslintrc.base.json',
]);
}
it('(React standalone) should set root project config to app and e2e app and migrate when another lib is added', () => {
const myapp = uniq('myapp');
const mylib = uniq('mylib');
runCLI(`generate @nx/react:app ${myapp} --rootProject=true`);
verifySuccessfulStandaloneSetup(myapp);
let appEslint = readJson('.eslintrc.json');
let e2eEslint = readJson('e2e/.eslintrc.json');
// should have plugin extends
expect(appEslint.overrides[0].extends).toBeDefined();
expect(appEslint.overrides[1].extends).toBeDefined();
expect(
e2eEslint.overrides.some((override) => override.extends)
).toBeTruthy();
runCLI(`generate @nx/js:lib ${mylib} --unitTestRunner=jest`);
verifySuccessfulMigratedSetup(myapp, mylib);
appEslint = readJson(`.eslintrc.json`);
e2eEslint = readJson('e2e/.eslintrc.json');
// should have no plugin extends
expect(appEslint.overrides[0].extends).toBeUndefined();
expect(appEslint.overrides[1].extends).toBeUndefined();
expect(
e2eEslint.overrides.some((override) => override.extends)
).toBeFalsy();
});
it('(Angular standalone) should set root project config to app and e2e app and migrate when another lib is added', () => {
const myapp = uniq('myapp');
const mylib = uniq('mylib');
runCLI(
`generate @nx/angular:app ${myapp} --rootProject=true --no-interactive`
);
verifySuccessfulStandaloneSetup(myapp);
let appEslint = readJson('.eslintrc.json');
let e2eEslint = readJson('e2e/.eslintrc.json');
// should have plugin extends
expect(appEslint.overrides[1].extends).toBeDefined();
expect(
e2eEslint.overrides.some((override) => override.extends)
).toBeTruthy();
runCLI(`generate @nx/js:lib ${mylib} --no-interactive`);
verifySuccessfulMigratedSetup(myapp, mylib);
appEslint = readJson(`.eslintrc.json`);
e2eEslint = readJson('e2e/.eslintrc.json');
// should have no plugin extends
expect(appEslint.overrides[1].extends).toEqual([
'plugin:@nx/angular-template',
]);
expect(
e2eEslint.overrides.some((override) => override.extends)
).toBeFalsy();
});
it('(Node standalone) should set root project config to app and e2e app and migrate when another lib is added', async () => {
const myapp = uniq('myapp');
const mylib = uniq('mylib');
runCLI(
`generate @nx/node:app ${myapp} --rootProject=true --no-interactive`
);
setMaxWorkers('project.json');
verifySuccessfulStandaloneSetup(myapp);
let appEslint = readJson('.eslintrc.json');
let e2eEslint = readJson('e2e/.eslintrc.json');
// should have plugin extends
expect(appEslint.overrides[0].extends).toBeDefined();
expect(appEslint.overrides[1].extends).toBeDefined();
expect(e2eEslint.overrides[0].extends).toBeDefined();
runCLI(`generate @nx/js:lib ${mylib} --no-interactive`);
verifySuccessfulMigratedSetup(myapp, mylib);
appEslint = readJson(`.eslintrc.json`);
e2eEslint = readJson('e2e/.eslintrc.json');
// should have no plugin extends
expect(appEslint.overrides[0].extends).toBeUndefined();
expect(appEslint.overrides[1].extends).toBeUndefined();
expect(e2eEslint.overrides[0].extends).toBeUndefined();
});
});
});
/**
* Update the generated rule implementation to produce a known lint error from all files.
*
* It is important that we do this surgically via AST transformations, otherwise we will
* drift further and further away from the original generated code and therefore make our
* e2e test less accurate and less valuable.
*/
function updateGeneratedRuleImplementation(
newRulePath: string,
newRuleGeneratedContents: string,
knownLintErrorMessage: string,
messageId,
libMethodName: string,
libPath: string
): string {
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
const newRuleSourceFile = ts.createSourceFile(
newRulePath,
newRuleGeneratedContents,
ts.ScriptTarget.Latest,
true
);
const transformer = <T extends ts.SourceFile>(
context: ts.TransformationContext
) =>
((rootNode: T) => {
function visit(node: ts.Node): ts.Node {
/**
* Add an ESLint messageId which will show the knownLintErrorMessage
*
* i.e.
*
* messages: {
* e2eMessageId: knownLintErrorMessage
* }
*/
if (
ts.isPropertyAssignment(node) &&
ts.isIdentifier(node.name) &&
node.name.escapedText === 'messages'
) {
return ts.factory.updatePropertyAssignment(
node,
node.name,
ts.factory.createObjectLiteralExpression([
ts.factory.createPropertyAssignment(
messageId,
ts.factory.createStringLiteral(knownLintErrorMessage)
),
])
);
}
/**
* Update the rule implementation to report the knownLintErrorMessage on every Program node
*
* During the debugging of the switch from ts-node to swc-node we found out
* that regular rules would work even without explicit path mapping registration,
* but rules that import runtime functionality from within the workspace
* would break the rule registration.
*
* Instead of having a static literal messageId we retreieved it via imported getMessageId method.
*
* i.e.
*
* create(context) {
* return {
* Program(node) {
* context.report({
* messageId: getMessageId(),
* node,
* });
* }
* }
* }
*/
if (
ts.isMethodDeclaration(node) &&
ts.isIdentifier(node.name) &&
node.name.escapedText === 'create'
) {
return ts.factory.updateMethodDeclaration(
node,
node.modifiers,
node.asteriskToken,
node.name,
node.questionToken,
node.typeParameters,
node.parameters,
node.type,
ts.factory.createBlock([
ts.factory.createReturnStatement(
ts.factory.createObjectLiteralExpression([
ts.factory.createMethodDeclaration(
[],
undefined,
'Program',
undefined,
[],
[
ts.factory.createParameterDeclaration(
[],
undefined,
'node',
undefined,
undefined,
undefined
),
],
undefined,
ts.factory.createBlock([
ts.factory.createExpressionStatement(
ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(
ts.factory.createIdentifier('context'),
'report'
),
[],
[
ts.factory.createObjectLiteralExpression([
ts.factory.createPropertyAssignment(
'messageId',
ts.factory.createCallExpression(
ts.factory.createIdentifier(libMethodName),
[],
[]
)
),
ts.factory.createShorthandPropertyAssignment(
'node'
),
]),
]
)
),
])
),
])
),
])
);
}
return ts.visitEachChild(node, visit, context);
}
/**
* Add lib import as a first line of the rule file.
* Needed for the access of getMessageId in the context report above.
*
* i.e.
*
* import { getMessageId } from "@myproj/mylib";
*
*/
const importAdded = ts.factory.updateSourceFile(rootNode, [
ts.factory.createImportDeclaration(
undefined,
ts.factory.createImportClause(
false,
undefined,
ts.factory.createNamedImports([
ts.factory.createImportSpecifier(
false,
undefined,
ts.factory.createIdentifier(libMethodName)
),
])
),
ts.factory.createStringLiteral(libPath)
),
...rootNode.statements,
]);
return ts.visitNode(importAdded, visit);
}) as ts.Transformer<T>;
const result: ts.TransformationResult<ts.SourceFile> =
ts.transform<ts.SourceFile>(newRuleSourceFile, [transformer]);
const updatedSourceFile: ts.SourceFile = result.transformed[0];
return printer.printFile(updatedSourceFile);
}
|
1,915 | 0 | petrpan-code/nrwl/nx/e2e/expo | petrpan-code/nrwl/nx/e2e/expo/src/expo.test.ts | import {
checkFilesExist,
cleanupProject,
expectTestsPass,
getPackageManagerCommand,
killPorts,
newProject,
promisifiedTreeKill,
readJson,
runCLI,
runCLIAsync,
runCommand,
runCommandUntil,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('expo', () => {
let proj: string;
let appName = uniq('my-app');
let libName = uniq('lib');
beforeAll(() => {
proj = newProject();
// we create empty preset above which skips creation of `production` named input
updateJson('nx.json', (nxJson) => {
nxJson.namedInputs = {
default: ['{projectRoot}/**/*', 'sharedGlobals'],
production: ['default'],
sharedGlobals: [],
};
nxJson.targetDefaults.build.inputs = ['production', '^production'];
return nxJson;
});
runCLI(`generate @nx/expo:application ${appName} --no-interactive`);
runCLI(
`generate @nx/expo:library ${libName} --buildable --publishable --importPath=${proj}/${libName}`
);
});
afterAll(() => cleanupProject());
it('should test and lint', async () => {
const componentName = uniq('Component');
runCLI(
`generate @nx/expo:component ${componentName} --project=${libName} --export --no-interactive`
);
updateFile(`apps/${appName}/src/app/App.tsx`, (content) => {
let updated = `// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport {${componentName}} from '${proj}/${libName}';\n${content}`;
return updated;
});
expectTestsPass(await runCLIAsync(`test ${appName}`));
expectTestsPass(await runCLIAsync(`test ${libName}`));
const appLintResults = await runCLIAsync(`lint ${appName}`);
expect(appLintResults.combinedOutput).toContain('All files pass linting.');
const libLintResults = await runCLIAsync(`lint ${libName}`);
expect(libLintResults.combinedOutput).toContain('All files pass linting.');
});
it('should export', async () => {
const exportResults = await runCLIAsync(
`export ${appName} --no-interactive`
);
expect(exportResults.combinedOutput).toContain(
'Export was successful. Your exported files can be found'
);
checkFilesExist(`dist/apps/${appName}/metadata.json`);
});
it('should export-web', async () => {
expect(() => {
runCLI(`export-web ${appName}`);
checkFilesExist(`apps/${appName}/dist/index.html`);
checkFilesExist(`apps/${appName}/dist/metadata.json`);
}).not.toThrow();
});
it('should prebuild', async () => {
// run prebuild command with git check disable
// set a mock package name for ios and android in expo's app.json
const root = `apps/${appName}`;
const appJsonPath = join(root, `app.json`);
const appJson = await readJson(appJsonPath);
if (appJson.expo.ios) {
appJson.expo.ios.bundleIdentifier = 'nx.test';
}
if (appJson.expo.android) {
appJson.expo.android.package = 'nx.test';
}
updateFile(appJsonPath, JSON.stringify(appJson));
// run prebuild command with git check disable
process.env['EXPO_NO_GIT_STATUS'] = 'true';
const prebuildResult = await runCLIAsync(
`prebuild ${appName} --no-interactive --install=false`
);
expect(prebuildResult.combinedOutput).toContain('Config synced');
});
it('should install', async () => {
// run install command
const installResults = await runCLIAsync(
`install ${appName} --no-interactive`
);
expect(installResults.combinedOutput).toContain(
'Successfully ran target install'
);
});
it('should start', async () => {
// run start command
const startProcess = await runCommandUntil(
`start ${appName} -- --port=8081`,
(output) =>
output.includes(`Packager is ready at http://localhost:8081`) ||
output.includes(`Web is waiting on http://localhost:8081`)
);
// port and process cleanup
try {
await promisifiedTreeKill(startProcess.pid, 'SIGKILL');
await killPorts(8081);
} catch (err) {
expect(err).toBeFalsy();
}
});
it('should build publishable library', async () => {
expect(() => {
runCLI(`build ${libName}`);
checkFilesExist(`dist/libs/${libName}/index.esm.js`);
checkFilesExist(`dist/libs/${libName}/src/index.d.ts`);
}).not.toThrow();
});
it('should tsc app', async () => {
expect(() => {
const pmc = getPackageManagerCommand();
runCommand(
`${pmc.runUninstalledPackage} tsc -p apps/${appName}/tsconfig.app.json`
);
checkFilesExist(
`dist/out-tsc/apps/${appName}/src/app/App.js`,
`dist/out-tsc/apps/${appName}/src/app/App.d.ts`,
`dist/out-tsc/libs/${libName}/src/index.js`,
`dist/out-tsc/libs/${libName}/src/index.d.ts`
);
}).not.toThrow();
});
it('should support generating projects with the new name and root format', () => {
const appName = uniq('app1');
const libName = uniq('@my-org/lib1');
runCLI(
`generate @nx/expo:application ${appName} --project-name-and-root-format=as-provided --no-interactive`
);
// check files are generated without the layout directory ("apps/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${appName}/src/app/App.tsx`);
// check tests pass
const appTestResult = runCLI(`test ${appName}`);
expect(appTestResult).toContain(
`Successfully ran target test for project ${appName}`
);
// assert scoped project names are not supported when --project-name-and-root-format=derived
expect(() =>
runCLI(
`generate @nx/expo:library ${libName} --buildable --project-name-and-root-format=derived`
)
).toThrow();
runCLI(
`generate @nx/expo:library ${libName} --buildable --project-name-and-root-format=as-provided`
);
// check files are generated without the layout directory ("libs/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${libName}/src/index.ts`);
// check tests pass
const libTestResult = runCLI(`test ${libName}`);
expect(libTestResult).toContain(
`Successfully ran target test for project ${libName}`
);
});
});
|
1,920 | 0 | petrpan-code/nrwl/nx/e2e/jest | petrpan-code/nrwl/nx/e2e/jest/src/jest-root.test.ts | import { newProject, runCLI, runCLIAsync, uniq } from '@nx/e2e/utils';
describe('Jest root projects', () => {
const myapp = uniq('myapp');
const mylib = uniq('mylib');
describe('angular', () => {
beforeAll(() => {
newProject();
});
it('should test root level app projects', async () => {
runCLI(
`generate @nx/angular:app ${myapp} --rootProject=true --no-interactive`
);
const rootProjectTestResults = await runCLIAsync(`test ${myapp}`);
expect(rootProjectTestResults.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
}, 300_000);
it('should add lib project and tests should still work', async () => {
runCLI(`generate @nx/angular:lib ${mylib} --no-interactive`);
runCLI(
`generate @nx/angular:component ${mylib} --export --standalone --project=${mylib} --no-interactive`
);
const libProjectTestResults = await runCLIAsync(`test ${mylib}`);
expect(libProjectTestResults.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
const rootProjectTestResults = await runCLIAsync(`test ${myapp}`);
expect(rootProjectTestResults.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
}, 300_000);
});
describe('react', () => {
beforeAll(() => {
newProject();
});
it('should test root level app projects', async () => {
runCLI(`generate @nx/react:app ${myapp} --rootProject=true`);
const rootProjectTestResults = await runCLIAsync(`test ${myapp}`);
expect(rootProjectTestResults.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
}, 300_000);
it('should add lib project and tests should still work', async () => {
runCLI(`generate @nx/react:lib ${mylib} --unitTestRunner=jest`);
const libProjectTestResults = await runCLIAsync(`test ${mylib}`);
expect(libProjectTestResults.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
const rootProjectTestResults = await runCLIAsync(`test ${myapp}`);
expect(rootProjectTestResults.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
}, 300_000);
});
});
|
1,921 | 0 | petrpan-code/nrwl/nx/e2e/jest | petrpan-code/nrwl/nx/e2e/jest/src/jest.test.ts | import { stripIndents } from '@angular-devkit/core/src/utils/literals';
import {
newProject,
runCLI,
runCLIAsync,
uniq,
updateFile,
expectJestTestsToPass,
cleanupProject,
} from '@nx/e2e/utils';
describe('Jest', () => {
beforeAll(() => {
newProject({ name: uniq('proj-jest') });
});
afterAll(() => cleanupProject());
it('should be able test projects using jest', async () => {
await expectJestTestsToPass('@nx/js:lib --unitTestRunner=jest');
}, 500000);
it('should merge with jest config globals', async () => {
const testGlobal = `'My Test Global'`;
const mylib = uniq('mylib');
const utilLib = uniq('util-lib');
runCLI(
`generate @nx/js:lib ${mylib} --unitTestRunner=jest --no-interactive`
);
runCLI(
`generate @nx/js:lib ${utilLib} --importPath=@global-fun/globals --unitTestRunner=jest --no-interactive`
);
updateFile(
`libs/${utilLib}/src/index.ts`,
stripIndents`
export function setup() {console.log('i am a global setup function')}
export function teardown() {console.log('i am a global teardown function')}
`
);
updateFile(`libs/${mylib}/src/lib/${mylib}.ts`, `export class Test { }`);
updateFile(
`libs/${mylib}/src/lib/${mylib}.spec.ts`,
`
test('can access jest global', () => {
expect((global as any).testGlobal).toBe(${testGlobal});
});
`
);
updateFile(
`libs/${mylib}/setup.ts`,
stripIndents`
const { registerTsProject } = require('@nx/js/src/internal');
const cleanup = registerTsProject('./tsconfig.base.json');
import {setup} from '@global-fun/globals';
export default async function() {setup();}
cleanup();
`
);
updateFile(
`libs/${mylib}/teardown.ts`,
stripIndents`
const { registerTsProject } = require('@nx/js/src/internal');
const cleanup = registerTsProject('./tsconfig.base.json');
import {teardown} from '@global-fun/globals';
export default async function() {teardown();}
cleanup();
`
);
updateFile(
`libs/${mylib}/jest.config.ts`,
stripIndents`
export default {
testEnvironment: 'node',
displayName: "${mylib}",
preset: "../../jest.preset.js",
transform: {
"^.+\\.[tj]s$": ["ts-jest", { tsconfig: "<rootDir>/tsconfig.spec.json" }],
},
moduleFileExtensions: ["ts", "js", "html"],
coverageDirectory: "../../coverage/libs/${mylib}",
globals: { testGlobal: ${testGlobal} },
globalSetup: '<rootDir>/setup.ts',
globalTeardown: '<rootDir>/teardown.ts'
};`
);
const appResult = await runCLIAsync(`test ${mylib} --no-watch`, {
silenceError: true,
});
expect(appResult.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
}, 300000);
it('should set the NODE_ENV to `test`', async () => {
const mylib = uniq('mylib');
runCLI(`generate @nx/js:lib ${mylib} --unitTestRunner=jest`);
updateFile(
`libs/${mylib}/src/lib/${mylib}.spec.ts`,
`
test('can access jest global', () => {
expect(process.env['NODE_ENV']).toBe('test');
});
`
);
const appResult = await runCLIAsync(`test ${mylib} --no-watch`);
expect(appResult.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
}, 90000);
it('should support multiple `coverageReporters` through CLI', async () => {
const mylib = uniq('mylib');
runCLI(`generate @nx/js:lib ${mylib} --unitTestRunner=jest`);
updateFile(
`libs/${mylib}/src/lib/${mylib}.spec.ts`,
`
test('can access jest global', () => {
expect(true).toBe(true);
});
`
);
const result = await runCLIAsync(
`test ${mylib} --no-watch --code-coverage --coverageReporters=text --coverageReporters=text-summary`
);
expect(result.stdout).toContain(
'File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s'
); // text
expect(result.stdout).toContain('Coverage summary'); // text-summary
}, 90000);
it('should be able to test node lib with babel-jest', async () => {
const libName = uniq('babel-test-lib');
runCLI(
`generate @nx/node:lib ${libName} --buildable --importPath=@some-org/babel-test --publishable --babelJest`
);
const cliResults = await runCLIAsync(`test ${libName}`);
expect(cliResults.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
}, 90000);
});
|
1,926 | 0 | petrpan-code/nrwl/nx/e2e/js | petrpan-code/nrwl/nx/e2e/js/src/js-executor-node.test.ts | import {
cleanupProject,
newProject,
runCLI,
setMaxWorkers,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('js:node executor', () => {
let scope: string;
beforeAll(() => {
scope = newProject();
});
afterAll(() => cleanupProject());
it('should log out the error', async () => {
const esbuildLib = uniq('esbuildlib');
runCLI(
`generate @nx/js:lib ${esbuildLib} --bundler=esbuild --no-interactive`
);
updateFile(`libs/${esbuildLib}/src/index.ts`, () => {
return `
console.log('Hello from my library!');
throw new Error('This is an error');
`;
});
updateJson(join('libs', esbuildLib, 'project.json'), (config) => {
config.targets['run-node'] = {
executor: '@nx/js:node',
options: {
buildTarget: `${esbuildLib}:build`,
watch: false,
},
};
return config;
});
const output = runCLI(`run ${esbuildLib}:run-node`, {
redirectStderr: true,
});
expect(output).toContain('Hello from my library!');
expect(output).toContain('This is an error');
}, 240_000);
it('should execute library compiled with rollup', async () => {
const rollupLib = uniq('rolluplib');
runCLI(
`generate @nx/js:lib ${rollupLib} --bundler=rollup --no-interactive`
);
updateFile(`libs/${rollupLib}/src/index.ts`, () => {
return `
console.log('Hello from my library!');
`;
});
updateJson(join('libs', rollupLib, 'project.json'), (config) => {
config.targets['run-node'] = {
executor: '@nx/js:node',
options: {
buildTarget: `${rollupLib}:build`,
watch: false,
},
};
return config;
});
const output = runCLI(`run ${rollupLib}:run-node`);
expect(output).toContain('Hello from my library!');
}, 240_000);
it('should execute library compiled with tsc', async () => {
const tscLib = uniq('tsclib');
runCLI(`generate @nx/js:lib ${tscLib} --bundler=tsc --no-interactive`);
updateFile(`libs/${tscLib}/src/index.ts`, () => {
return `
console.log('Hello from my tsc library!');
`;
});
updateJson(join('libs', tscLib, 'project.json'), (config) => {
config.targets['run-node'] = {
executor: '@nx/js:node',
options: {
buildTarget: `${tscLib}:build`,
watch: false,
},
};
return config;
});
const output = runCLI(`run ${tscLib}:run-node`);
expect(output).toContain('Hello from my tsc library!');
}, 240_000);
it('should execute library compiled with swc', async () => {
const swcLib = uniq('swclib');
runCLI(`generate @nx/js:lib ${swcLib} --bundler=swc --no-interactive`);
updateFile(`libs/${swcLib}/src/index.ts`, () => {
return `
console.log('Hello from my swc library!');
`;
});
updateJson(join('libs', swcLib, 'project.json'), (config) => {
config.targets['run-node'] = {
executor: '@nx/js:node',
options: {
buildTarget: `${swcLib}:build`,
watch: false,
},
};
return config;
});
const output = runCLI(`run ${swcLib}:run-node`);
expect(output).toContain('Hello from my swc library!');
}, 240_000);
it('should execute webpack app', async () => {
const webpackProject = uniq('webpackproject');
runCLI(
`generate @nx/node:application ${webpackProject} --bundler=webpack --no-interactive`
);
setMaxWorkers(join('apps', webpackProject, 'project.json'));
updateFile(`apps/${webpackProject}/src/main.ts`, () => {
return `
console.log('Hello from my webpack app!');
`;
});
updateJson(join('apps', webpackProject, 'project.json'), (config) => {
config.targets['run-node'] = {
executor: '@nx/js:node',
options: {
buildTarget: `${webpackProject}:build`,
watch: false,
},
};
config.targets.build = {
...config.targets.build,
configurations: {
development: {
outputPath: 'dist/packages/api-dev',
},
production: {
outputPath: 'dist/packages/api-prod',
},
},
};
return config;
});
const output = runCLI(`run ${webpackProject}:run-node`);
expect(output).toContain('Hello from my webpack app!');
}, 240_000);
});
|
1,927 | 0 | petrpan-code/nrwl/nx/e2e/js | petrpan-code/nrwl/nx/e2e/js/src/js-executor-swc.test.ts | import { execSync } from 'child_process';
import {
checkFilesExist,
cleanupProject,
detectPackageManager,
newProject,
packageManagerLockFile,
readJson,
runCLI,
tmpProjPath,
uniq,
updateFile,
updateJson,
} from '../../utils';
describe('js:swc executor', () => {
let scope: string;
beforeAll(() => {
scope = newProject();
});
afterAll(() => {
cleanupProject();
});
it('should create libs with js executors (--bundler=swc)', async () => {
const lib = uniq('lib');
runCLI(`generate @nx/js:lib ${lib} --bundler=swc --no-interactive`);
const libPackageJson = readJson(`libs/${lib}/package.json`);
expect(libPackageJson.scripts).toBeUndefined();
expect(runCLI(`build ${lib}`)).toContain(
'Successfully compiled: 2 files with swc'
);
checkFilesExist(
`dist/libs/${lib}/package.json`,
`dist/libs/${lib}/src/index.js`,
`dist/libs/${lib}/src/lib/${lib}.js`,
`dist/libs/${lib}/src/index.d.ts`,
`dist/libs/${lib}/src/lib/${lib}.d.ts`
);
const tsconfig = readJson(`tsconfig.base.json`);
expect(tsconfig.compilerOptions.paths).toEqual({
[`@${scope}/${lib}`]: [`libs/${lib}/src/index.ts`],
});
}, 240_000);
it('should handle swcrc path mappings', async () => {
const lib = uniq('lib');
runCLI(`generate @nx/js:lib ${lib} --bundler=swc --no-interactive`);
// add a dummy x.ts file for path mappings
updateFile(
`libs/${lib}/src/x.ts`,
`
export function x() {
console.log('x');
}
`
);
// update .swcrc to use path mappings
updateJson(`libs/${lib}/.swcrc`, (json) => {
json.jsc.baseUrl = '.';
json.jsc.paths = {
'~/*': ['./src/*'],
};
return json;
});
// update lib.ts to use x
updateFile(`libs/${lib}/src/lib/${lib}.ts`, () => {
return `
// @ts-ignore
import { x } from '~/x';
export function myLib() {
console.log(x());
}
myLib();
`;
});
// now run build without type checking (since we're using path mappings not in tsconfig)
runCLI(`build ${lib} --skipTypeCheck`);
// invoke the lib with node
const result = execSync(`node dist/libs/${lib}/src/lib/${lib}.js`, {
cwd: tmpProjPath(),
}).toString();
expect(result).toContain('x');
}, 240_000);
});
|
1,928 | 0 | petrpan-code/nrwl/nx/e2e/js | petrpan-code/nrwl/nx/e2e/js/src/js-executor-tsc.test.ts | import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
createFile,
detectPackageManager,
getPackageManagerCommand,
newProject,
packageManagerLockFile,
readFile,
readJson,
rmDist,
runCLI,
runCLIAsync,
runCommand,
runCommandUntil,
tmpProjPath,
uniq,
updateFile,
updateJson,
waitUntil,
} from '../../utils';
describe('js:tsc executor', () => {
let scope;
beforeAll(() => (scope = newProject()));
afterAll(() => cleanupProject());
it('should create libs with js executors (--compiler=tsc)', async () => {
const lib = uniq('lib');
runCLI(`generate @nx/js:lib ${lib} --bundler=tsc --no-interactive`);
const libPackageJson = readJson(`libs/${lib}/package.json`);
expect(libPackageJson.scripts).toBeUndefined();
expect(runCLI(`build ${lib}`)).toContain('Done compiling TypeScript files');
checkFilesExist(
`dist/libs/${lib}/README.md`,
`dist/libs/${lib}/package.json`,
`dist/libs/${lib}/src/index.js`,
`dist/libs/${lib}/src/lib/${lib}.js`,
`dist/libs/${lib}/src/index.d.ts`,
`dist/libs/${lib}/src/lib/${lib}.d.ts`
);
runCLI(`build ${lib} --generateLockfile=true`);
checkFilesExist(
`dist/libs/${lib}/package.json`,
`dist/libs/${lib}/${
packageManagerLockFile[detectPackageManager(tmpProjPath())]
}`
);
updateJson(`libs/${lib}/project.json`, (json) => {
json.targets.build.options.assets.push({
input: `libs/${lib}/docs`,
glob: '**/*.md',
output: 'docs',
});
return json;
});
const libBuildProcess = await runCommandUntil(
`build ${lib} --watch`,
(output) => output.includes(`Watching for file changes`)
);
updateFile(`libs/${lib}/README.md`, `Hello, World!`);
updateJson(`libs/${lib}/package.json`, (json) => {
json.version = '999.9.9';
return json;
});
updateFile(`libs/${lib}/docs/a/b/nested.md`, 'Nested File');
await expect(
waitUntil(
() => readFile(`dist/libs/${lib}/README.md`).includes(`Hello, World!`),
{
timeout: 20_000,
ms: 500,
}
)
).resolves.not.toThrow();
await expect(
waitUntil(
() =>
readFile(`dist/libs/${lib}/docs/a/b/nested.md`).includes(
`Nested File`
),
{
timeout: 20_000,
ms: 500,
}
)
).resolves.not.toThrow();
await expect(
waitUntil(
() =>
readFile(`dist/libs/${lib}/package.json`).includes(
`"version": "999.9.9"`
),
{
timeout: 20_000,
ms: 500,
}
)
).resolves.not.toThrow();
libBuildProcess.kill();
const parentLib = uniq('parentlib');
runCLI(`generate @nx/js:lib ${parentLib} --bundler=tsc --no-interactive`);
const parentLibPackageJson = readJson(`libs/${parentLib}/package.json`);
expect(parentLibPackageJson.scripts).toBeUndefined();
expect((await runCLIAsync(`test ${parentLib}`)).combinedOutput).toContain(
'Ran all test suites'
);
expect(runCLI(`build ${parentLib}`)).toContain(
'Done compiling TypeScript files'
);
checkFilesExist(
`dist/libs/${parentLib}/package.json`,
`dist/libs/${parentLib}/src/index.js`,
`dist/libs/${parentLib}/src/lib/${parentLib}.js`,
`dist/libs/${parentLib}/src/index.d.ts`,
`dist/libs/${parentLib}/src/lib/${parentLib}.d.ts`
);
const tsconfig = readJson(`tsconfig.base.json`);
expect(tsconfig.compilerOptions.paths).toEqual({
[`@${scope}/${lib}`]: [`libs/${lib}/src/index.ts`],
[`@${scope}/${parentLib}`]: [`libs/${parentLib}/src/index.ts`],
});
updateFile(`libs/${parentLib}/src/index.ts`, () => {
return `
import { ${lib} } from '@${scope}/${lib}'
export * from './lib/${parentLib}';
`;
});
const output = runCLI(`build ${parentLib}`);
expect(output).toContain('1 task it depends on');
expect(output).toContain('Done compiling TypeScript files');
updateJson(`libs/${lib}/tsconfig.json`, (json) => {
json.compilerOptions = { ...json.compilerOptions, importHelpers: true };
return json;
});
updateJson(`libs/${lib}/package.json`, (json) => {
// Delete automatically generated helper dependency to test legacy behavior.
delete json.dependencies.tslib;
return json;
});
// check batch build
rmDist();
let batchBuildOutput = runCLI(`build ${parentLib} --skip-nx-cache`, {
env: { NX_BATCH_MODE: 'true' },
});
expect(batchBuildOutput).toContain(`Running 2 tasks with @nx/js:tsc`);
expect(batchBuildOutput).toContain(
`Compiling TypeScript files for project "${lib}"...`
);
expect(batchBuildOutput).toContain(
`Done compiling TypeScript files for project "${lib}".`
);
expect(batchBuildOutput).toContain(
`Compiling TypeScript files for project "${parentLib}"...`
);
expect(batchBuildOutput).toContain(
`Done compiling TypeScript files for project "${parentLib}".`
);
expect(batchBuildOutput).toContain(
`Successfully ran target build for project ${parentLib} and 1 task it depends on`
);
batchBuildOutput = runCLI(`build ${parentLib} --skip-nx-cache --batch`);
expect(batchBuildOutput).toContain(`Running 2 tasks with @nx/js:tsc`);
checkFilesExist(
// parent
`dist/libs/${parentLib}/package.json`,
`dist/libs/${parentLib}/README.md`,
`dist/libs/${parentLib}/tsconfig.tsbuildinfo`,
`dist/libs/${parentLib}/src/index.js`,
`dist/libs/${parentLib}/src/index.d.ts`,
`dist/libs/${parentLib}/src/lib/${parentLib}.js`,
`dist/libs/${parentLib}/src/lib/${parentLib}.d.ts`,
// child
`dist/libs/${lib}/package.json`,
`dist/libs/${lib}/README.md`,
`dist/libs/${lib}/tsconfig.tsbuildinfo`,
`dist/libs/${lib}/src/index.js`,
`dist/libs/${lib}/src/index.d.ts`,
`dist/libs/${lib}/src/lib/${lib}.js`,
`dist/libs/${lib}/src/lib/${lib}.d.ts`
);
// run a second time skipping the nx cache and with the outputs present
const secondBatchBuildOutput = runCLI(
`build ${parentLib} --skip-nx-cache`,
{ env: { NX_BATCH_MODE: 'true' } }
);
expect(secondBatchBuildOutput).toContain(
`Successfully ran target build for project ${parentLib} and 1 task it depends on`
);
}, 240_000);
it('should not create a `.babelrc` file when creating libs with js executors (--compiler=tsc)', () => {
const lib = uniq('lib');
runCLI(
`generate @nx/js:lib ${lib} --compiler=tsc --includeBabelRc=false --no-interactive`
);
checkFilesDoNotExist(`libs/${lib}/.babelrc`);
});
it('should allow wildcard ts path alias', async () => {
const base = uniq('base');
runCLI(`generate @nx/js:lib ${base} --bundler=tsc --no-interactive`);
const lib = uniq('lib');
runCLI(`generate @nx/js:lib ${lib} --bundler=tsc --no-interactive`);
updateFile(`libs/${base}/src/index.ts`, () => {
return `
import { ${lib} } from '@${scope}/${lib}'
export * from './lib/${base}';
${lib}();
`;
});
expect(runCLI(`build ${base}`)).toContain(
'Done compiling TypeScript files'
);
updateJson('tsconfig.base.json', (json) => {
json['compilerOptions']['paths'][`@${scope}/${lib}/*`] = [
`libs/${lib}/src/*`,
];
return json;
});
createFile(
`libs/${lib}/src/${lib}.ts`,
`
export function ${lib}Wildcard() {
return '${lib}-wildcard';
};
`
);
updateFile(`libs/${base}/src/index.ts`, () => {
return `
import { ${lib} } from '@${scope}/${lib}';
import { ${lib}Wildcard } from '@${scope}/${lib}/src/${lib}';
export * from './lib/${base}';
${lib}();
${lib}Wildcard();
`;
});
expect(runCLI(`build ${base}`)).toContain(
'Done compiling TypeScript files'
);
}, 240_000);
it('should update package.json with detected dependencies', async () => {
const pmc = getPackageManagerCommand();
const lib = uniq('lib');
runCLI(`generate @nx/js:lib ${lib} --bundler=tsc --no-interactive`);
// Add a dependency for this lib to check the built package.json
runCommand(`${pmc.addProd} react`);
runCommand(`${pmc.addDev} @types/react`);
updateFile(`libs/${lib}/src/index.ts`, (content) => {
return `
import 'react';
${content};
`;
});
}, 240_000);
});
|
1,930 | 0 | petrpan-code/nrwl/nx/e2e/js | petrpan-code/nrwl/nx/e2e/js/src/js-inlining.test.ts | import {
checkFilesExist,
cleanupProject,
newProject,
readFile,
runCLI,
uniq,
updateFile,
} from '@nx/e2e/utils';
import { execSync } from 'child_process';
describe('inlining', () => {
let scope: string;
beforeAll(() => {
scope = newProject();
});
afterAll(() => cleanupProject());
it.each(['tsc', 'swc'])(
'should inline libraries with --bundler=%s',
async (bundler) => {
const parent = uniq('parent');
runCLI(
`generate @nx/js:lib ${parent} --bundler=${bundler} --no-interactive`
);
const buildable = uniq('buildable');
runCLI(
`generate @nx/js:lib ${buildable} --bundler=${bundler} --no-interactive`
);
const buildableTwo = uniq('buildabletwo');
runCLI(
`generate @nx/js:lib ${buildableTwo} --bundler=${bundler} --no-interactive`
);
const nonBuildable = uniq('nonbuildable');
runCLI(
`generate @nx/js:lib ${nonBuildable} --bundler=none --no-interactive`
);
updateFile(`libs/${parent}/src/lib/${parent}.ts`, () => {
return `
import { ${buildable} } from '@${scope}/${buildable}';
import { ${buildableTwo} } from '@${scope}/${buildableTwo}';
import { ${nonBuildable} } from '@${scope}/${nonBuildable}';
export function ${parent}() {
${buildable}();
${buildableTwo}();
${nonBuildable}();
}
`;
});
// 1. external is set to all
execSync(`rm -rf dist`);
runCLI(`build ${parent} --external=all`);
checkFilesExist(
`dist/libs/${buildable}/src/index.js`, // buildable
`dist/libs/${buildableTwo}/src/index.js`, // buildable two
`dist/libs/${parent}/src/index.js`, // parent
`dist/libs/${parent}/${nonBuildable}/src/index.js` // inlined non buildable
);
// non-buildable lib import path is modified to relative path
let fileContent = readFile(`dist/libs/${parent}/src/lib/${parent}.js`);
expect(fileContent).toContain(`${nonBuildable}/src`);
// 2. external is set to none
execSync(`rm -rf dist`);
runCLI(`build ${parent} --external=none`);
checkFilesExist(
`dist/libs/${parent}/src/index.js`, // parent
`dist/libs/${parent}/${buildable}/src/index.js`, // inlined buildable
`dist/libs/${parent}/${buildableTwo}/src/index.js`, // inlined buildable two
`dist/libs/${parent}/${nonBuildable}/src/index.js` // inlined non buildable
);
fileContent = readFile(`dist/libs/${parent}/src/lib/${parent}.js`);
expect(fileContent).toContain(`${nonBuildable}/src`);
expect(fileContent).toContain(`${buildable}/src`);
expect(fileContent).toContain(`${buildableTwo}/src`);
// 3. external is set to an array of libs
execSync(`rm -rf dist`);
runCLI(`build ${parent} --external=${buildable}`);
checkFilesExist(
`dist/libs/${buildable}/src/index.js`, // buildable
`dist/libs/${buildableTwo}/src/index.js`, // buildable two original output should be persisted
`dist/libs/${parent}/src/index.js`, // parent
`dist/libs/${parent}/${buildableTwo}/src/index.js`, // inlined buildable two
`dist/libs/${parent}/${nonBuildable}/src/index.js` // inlined non buildable
);
fileContent = readFile(`dist/libs/${parent}/src/lib/${parent}.js`);
expect(fileContent).toContain(`${nonBuildable}/src`);
expect(fileContent).toContain(`${buildableTwo}/src`);
expect(fileContent).not.toContain(`${buildable}/src`);
},
240_000
);
it('should inline nesting libraries', async () => {
const parent = uniq('parent');
runCLI(`generate @nx/js:lib ${parent} --no-interactive`);
const child = uniq('child');
runCLI(`generate @nx/js:lib ${child} --bundler=none --no-interactive`);
const grandChild = uniq('grandchild');
runCLI(`generate @nx/js:lib ${grandChild} --bundler=none --no-interactive`);
updateFile(`libs/${parent}/src/lib/${parent}.ts`, () => {
return `
import { ${child} } from '@${scope}/${child}';
export function ${parent}() {
${child}();
}
`;
});
updateFile(`libs/${child}/src/lib/${child}.ts`, () => {
return `
import { ${grandChild} } from '@${scope}/${grandChild}';
export function ${child}() {
${grandChild}();
}
`;
});
runCLI(`build ${parent} --external=all`);
checkFilesExist(
`dist/libs/${parent}/src/index.js`, // parent
`dist/libs/${parent}/${child}/src/index.js`, // inlined child
`dist/libs/${parent}/${grandChild}/src/index.js` // inlined grand child
);
// non-buildable lib import path is modified to relative path
const parentFileContent = readFile(
`dist/libs/${parent}/src/lib/${parent}.js`
);
expect(parentFileContent).toContain(`${child}/src`);
expect(parentFileContent).not.toContain(`${grandChild}/src`);
const childFileContent = readFile(
`dist/libs/${parent}/${child}/src/lib/${child}.js`
);
expect(childFileContent).toContain(`${grandChild}/src`);
}, 240_000);
});
|
1,931 | 0 | petrpan-code/nrwl/nx/e2e/js | petrpan-code/nrwl/nx/e2e/js/src/js-packaging.test.ts | import {
updateJson,
cleanupProject,
newProject,
runCLI,
tmpProjPath,
runCommand,
createFile,
uniq,
getPackageManagerCommand,
readJson,
updateFile,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('packaging libs', () => {
let scope: string;
beforeEach(() => {
scope = newProject();
});
afterEach(() => cleanupProject());
it('should bundle libs using esbuild, vite, rollup and be used in CJS/ESM projects', () => {
const esbuildLib = uniq('esbuildlib');
const viteLib = uniq('vitelib');
const rollupLib = uniq('rolluplib');
runCLI(
`generate @nx/js:lib ${esbuildLib} --bundler=esbuild --no-interactive`
);
runCLI(`generate @nx/js:lib ${viteLib} --bundler=vite --no-interactive`);
runCLI(
`generate @nx/js:lib ${rollupLib} --bundler=rollup --no-interactive`
);
updateFile(`libs/${rollupLib}/src/index.ts`, (content) => {
// Test that default functions work in ESM (Node).
return `${content}\nexport default function f() { return 'rollup default' }`;
});
runCLI(`build ${esbuildLib}`);
runCLI(`build ${viteLib}`);
runCLI(`build ${rollupLib} --generateExportsField`);
const pmc = getPackageManagerCommand();
let output: string;
// Make sure outputs in commonjs project
createFile(
'test-cjs/package.json',
JSON.stringify(
{
name: 'test-cjs',
private: true,
type: 'commonjs',
dependencies: {
[`@proj/${esbuildLib}`]: `file:../dist/libs/${esbuildLib}`,
[`@proj/${viteLib}`]: `file:../dist/libs/${viteLib}`,
[`@proj/${rollupLib}`]: `file:../dist/libs/${rollupLib}`,
},
},
null,
2
)
);
createFile(
'test-cjs/index.js',
`
const { ${esbuildLib} } = require('@proj/${esbuildLib}');
const { ${viteLib} } = require('@proj/${viteLib}');
const { default: rollupDefault, ${rollupLib} } = require('@proj/${rollupLib}');
console.log(${esbuildLib}());
console.log(${viteLib}());
console.log(${rollupLib}());
console.log(rollupDefault());
`
);
runCommand(pmc.install, {
cwd: join(tmpProjPath(), 'test-cjs'),
});
output = runCommand('node index.js', {
cwd: join(tmpProjPath(), 'test-cjs'),
});
expect(output).toContain(esbuildLib);
expect(output).toContain(viteLib);
expect(output).toContain(rollupLib);
expect(output).toContain('rollup default');
// Make sure outputs in esm project
createFile(
'test-esm/package.json',
JSON.stringify(
{
name: 'test-esm',
private: true,
type: 'module',
dependencies: {
[`@proj/${esbuildLib}`]: `file:../dist/libs/${esbuildLib}`,
[`@proj/${viteLib}`]: `file:../dist/libs/${viteLib}`,
[`@proj/${rollupLib}`]: `file:../dist/libs/${rollupLib}`,
},
},
null,
2
)
);
createFile(
'test-esm/index.js',
`
import { ${esbuildLib} } from '@proj/${esbuildLib}';
import { ${viteLib} } from '@proj/${viteLib}';
import rollupDefault, { ${rollupLib} } from '@proj/${rollupLib}';
console.log(${esbuildLib}());
console.log(${viteLib}());
console.log(${rollupLib}());
console.log(rollupDefault());
`
);
runCommand(pmc.install, {
cwd: join(tmpProjPath(), 'test-esm'),
});
output = runCommand('node index.js', {
cwd: join(tmpProjPath(), 'test-esm'),
});
expect(output).toContain(esbuildLib);
expect(output).toContain(viteLib);
expect(output).toContain(rollupLib);
expect(output).toContain('rollup default');
}, 500_000);
it('should build with tsc, swc and be used in CJS/ESM projects', async () => {
const tscLib = uniq('tsclib');
const swcLib = uniq('swclib');
const tscEsmLib = uniq('tscesmlib');
const swcEsmLib = uniq('swcesmlib');
runCLI(`generate @nx/js:lib ${tscLib} --bundler=tsc --no-interactive`);
runCLI(`generate @nx/js:lib ${swcLib} --bundler=swc --no-interactive`);
runCLI(`generate @nx/js:lib ${tscEsmLib} --bundler=tsc --no-interactive`);
runCLI(`generate @nx/js:lib ${swcEsmLib} --bundler=swc --no-interactive`);
// Change module format to ESM
updateJson(`libs/${tscEsmLib}/tsconfig.json`, (json) => {
json.compilerOptions.module = 'esnext';
return json;
});
updateJson(`libs/${swcEsmLib}/.swcrc`, (json) => {
json.module.type = 'es6';
return json;
});
// Node ESM requires file extensions in imports so must add them before building
updateFile(
`libs/${tscEsmLib}/src/index.ts`,
`export * from './lib/${tscEsmLib}.js';`
);
updateFile(
`libs/${swcEsmLib}/src/index.ts`,
`export * from './lib/${swcEsmLib}.js';`
);
// Add additional entry points for `exports` field
updateJson(join('libs', tscLib, 'project.json'), (json) => {
json.targets.build.options.additionalEntryPoints = [
`libs/${tscLib}/src/foo/*.ts`,
];
return json;
});
updateFile(`libs/${tscLib}/src/foo/bar.ts`, `export const bar = 'bar';`);
updateFile(`libs/${tscLib}/src/foo/faz.ts`, `export const faz = 'faz';`);
updateJson(join('libs', swcLib, 'project.json'), (json) => {
json.targets.build.options.additionalEntryPoints = [
`libs/${swcLib}/src/foo/*.ts`,
];
return json;
});
updateFile(`libs/${swcLib}/src/foo/bar.ts`, `export const bar = 'bar';`);
updateFile(`libs/${swcLib}/src/foo/faz.ts`, `export const faz = 'faz';`);
runCLI(`build ${tscLib} --generateExportsField`);
runCLI(`build ${swcLib} --generateExportsField`);
runCLI(`build ${tscEsmLib} --generateExportsField`);
runCLI(`build ${swcEsmLib} --generateExportsField`);
expect(readJson(`dist/libs/${tscLib}/package.json`).exports).toEqual({
'./package.json': './package.json',
'.': './src/index.js',
'./foo/bar': './src/foo/bar.js',
'./foo/faz': './src/foo/faz.js',
});
expect(readJson(`dist/libs/${swcLib}/package.json`).exports).toEqual({
'./package.json': './package.json',
'.': './src/index.js',
'./foo/bar': './src/foo/bar.js',
'./foo/faz': './src/foo/faz.js',
});
const pmc = getPackageManagerCommand();
let output: string;
// Make sure CJS output is correct
createFile(
'test-cjs/package.json',
JSON.stringify(
{
name: 'test-cjs',
private: true,
type: 'commonjs',
dependencies: {
[`@proj/${tscLib}`]: `file:../dist/libs/${tscLib}`,
[`@proj/${swcLib}`]: `file:../dist/libs/${swcLib}`,
},
},
null,
2
)
);
createFile(
'test-cjs/index.js',
`
const { ${tscLib} } = require('@proj/${tscLib}');
const { ${swcLib} } = require('@proj/${swcLib}');
// additional entry-points
const { bar } = require('@proj/${tscLib}/foo/bar');
const { faz } = require('@proj/${swcLib}/foo/faz');
console.log(${tscLib}());
console.log(${swcLib}());
console.log(bar);
console.log(faz);
`
);
runCommand(pmc.install, {
cwd: join(tmpProjPath(), 'test-cjs'),
});
output = runCommand('node index.js', {
cwd: join(tmpProjPath(), 'test-cjs'),
});
expect(output).toContain(tscLib);
expect(output).toContain(swcLib);
expect(output).toContain('bar');
expect(output).toContain('faz');
// Make sure ESM output is correct
createFile(
'test-esm/package.json',
JSON.stringify(
{
name: 'test-esm',
private: true,
type: 'module',
dependencies: {
[`@proj/${tscEsmLib}`]: `file:../dist/libs/${tscEsmLib}`,
[`@proj/${swcEsmLib}`]: `file:../dist/libs/${swcEsmLib}`,
},
},
null,
2
)
);
createFile(
'test-esm/index.js',
`
import { ${tscEsmLib} } from '@proj/${tscEsmLib}';
import { ${swcEsmLib} } from '@proj/${swcEsmLib}';
console.log(${tscEsmLib}());
console.log(${swcEsmLib}());
`
);
runCommand(pmc.install, {
cwd: join(tmpProjPath(), 'test-esm'),
});
output = runCommand('node index.js', {
cwd: join(tmpProjPath(), 'test-esm'),
});
expect(output).toContain(tscEsmLib);
expect(output).toContain(swcEsmLib);
}, 500_000);
});
|
1,936 | 0 | petrpan-code/nrwl/nx/e2e/lerna-smoke-tests | petrpan-code/nrwl/nx/e2e/lerna-smoke-tests/src/lerna-smoke-tests.test.ts | /**
* These minimal smoke tests are here to ensure that we do not break assumptions on the lerna side
* when making updates to nx or @nx/devkit.
*/
import {
cleanupProject,
newLernaWorkspace,
runLernaCLI,
tmpProjPath,
updateJson,
} from '@nx/e2e/utils';
expect.addSnapshotSerializer({
serialize(str: string) {
return (
str
// Not all package managers print the package.json path in the output
.replace(tmpProjPath(), '')
.replace('/private', '')
.replace('/packages/package-1', '')
// We trim each line to reduce the chances of snapshot flakiness
.split('\n')
.map((r) => r.trim())
.join('\n')
);
},
test(val: string) {
return val != null && typeof val === 'string';
},
});
describe('Lerna Smoke Tests', () => {
beforeAll(() => newLernaWorkspace());
afterAll(() => cleanupProject({ skipReset: true }));
// `lerna repair` builds on top of `nx repair` and runs all of its generators
describe('lerna repair', () => {
// If this snapshot fails it means that nx repair generators are making assumptions which don't hold true for lerna workspaces
it('should complete successfully on a new lerna workspace', async () => {
let result = runLernaCLI(`repair`);
result = result.replace(/.*\/node_modules\/.*\n/, ''); // yarn adds "$ /node_modules/.bin/lerna repair" to the output
expect(result).toMatchInlineSnapshot(`
> Lerna No changes were necessary. This workspace is up to date!
`);
}, 1000000);
});
// `lerna run` delegates to the nx task runner behind the scenes
describe('lerna run', () => {
it('should complete successfully on a new lerna workspace', async () => {
runLernaCLI('create package-1 -y');
updateJson('packages/package-1/package.json', (json) => ({
...json,
scripts: {
...(json.scripts || {}),
'print-name': 'echo test-package-1',
},
}));
let result = runLernaCLI(`run print-name`);
result = result
.replace(/.*\/node_modules\/.*\n/, '') // yarn adds "$ /node_modules/.bin/lerna run print-name" to the output
.replace(/.*package-1@0.*\n/, '') // yarn output doesn't contain "> [email protected] print-name"
.replace('$ echo test-package-1', '> echo test-package-1');
expect(result).toMatchInlineSnapshot(`
> package-1:print-name
> echo test-package-1
test-package-1
> Lerna (powered by Nx) Successfully ran target print-name for project package-1
`);
}, 1000000);
});
});
|
1,941 | 0 | petrpan-code/nrwl/nx/e2e/next-core | petrpan-code/nrwl/nx/e2e/next-core/src/next-appdir.test.ts | import {
cleanupProject,
isNotWindows,
newProject,
runCLI,
uniq,
updateFile,
} from '@nx/e2e/utils';
import { checkApp } from './utils';
describe('Next.js App Router', () => {
let proj: string;
beforeAll(() => (proj = newProject()));
afterAll(() => cleanupProject());
// TODO: enable this when tests are passing again
xit('should be able to generate and build app with default App Router', async () => {
const appName = uniq('app');
const jsLib = uniq('tslib');
runCLI(
`generate @nx/next:app ${appName} --e2eTestRunner=playwright --appDir=true`
);
runCLI(`generate @nx/js:lib ${jsLib} --no-interactive`);
updateFile(
`apps/${appName}/app/page.tsx`,
`
import React from 'react';
import { ${jsLib} } from '@${proj}/${jsLib}';
export default async function Page() {
return (
<p>{${jsLib}()}</p>
);
};
`
);
updateFile(
`apps/${appName}-e2e/src/example.spec.ts`,
`
import { test, expect } from '@playwright/test';
test('has ${jsLib}', async ({ page }) => {
await page.goto('/');
// Expect h1 to contain a substring.
expect(await page.locator('p').innerText()).toContain('${jsLib}');
});
`
);
await checkApp(appName, {
checkUnitTest: false,
checkLint: true,
checkE2E: isNotWindows(),
checkExport: false,
});
}, 300_000);
});
|
1,942 | 0 | petrpan-code/nrwl/nx/e2e/next-core | petrpan-code/nrwl/nx/e2e/next-core/src/next-lock-file.test.ts | import { detectPackageManager, joinPathFragments } from '@nx/devkit';
import {
checkFilesExist,
cleanupProject,
getPackageManagerCommand,
newProject,
packageManagerLockFile,
runCLI,
runCommand,
tmpProjPath,
uniq,
} from '@nx/e2e/utils';
describe('Next.js Lock File', () => {
let proj: string;
let originalEnv: string;
let packageManager;
beforeEach(() => {
proj = newProject();
packageManager = detectPackageManager(tmpProjPath());
originalEnv = process.env.NODE_ENV;
});
afterEach(() => {
process.env.NODE_ENV = originalEnv;
cleanupProject();
});
it('should build and install pruned lock file', () => {
const appName = uniq('app');
runCLI(`generate @nx/next:app ${appName} --no-interactive --style=css`);
const result = runCLI(`build ${appName} --generateLockfile=true`);
expect(result).not.toMatch(/Graph is not consistent/);
checkFilesExist(
`dist/apps/${appName}/${packageManagerLockFile[packageManager]}`
);
runCommand(`${getPackageManagerCommand().ciInstall}`, {
cwd: joinPathFragments(tmpProjPath(), 'dist/apps', appName),
});
}, 1_000_000);
});
|
1,943 | 0 | petrpan-code/nrwl/nx/e2e/next-core | petrpan-code/nrwl/nx/e2e/next-core/src/next-structure.test.ts | import { mkdirSync, removeSync } from 'fs-extra';
import { capitalize } from '@nx/devkit/src/utils/string-utils';
import { checkApp } from './utils';
import {
checkFilesExist,
cleanupProject,
isNotWindows,
killPort,
newProject,
readFile,
runCLI,
runCommandUntil,
tmpProjPath,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('Next.js Apps Libs', () => {
let proj: string;
let originalEnv: string;
beforeEach(() => {
proj = newProject();
originalEnv = process.env.NODE_ENV;
});
afterEach(() => {
process.env.NODE_ENV = originalEnv;
cleanupProject();
});
it('should generate app + libs', async () => {
// Remove apps/libs folder and use packages.
// Allows us to test other integrated monorepo setup that had a regression.
// See: https://github.com/nrwl/nx/issues/16658
removeSync(`${tmpProjPath()}/libs`);
removeSync(`${tmpProjPath()}/apps`);
mkdirSync(`${tmpProjPath()}/packages`);
const appName = uniq('app');
const nextLib = uniq('nextlib');
const jsLib = uniq('tslib');
const buildableLib = uniq('buildablelib');
runCLI(
`generate @nx/next:app ${appName} --no-interactive --style=css --appDir=false`
);
runCLI(`generate @nx/next:lib ${nextLib} --no-interactive`);
runCLI(`generate @nx/js:lib ${jsLib} --no-interactive`);
runCLI(
`generate @nx/js:lib ${buildableLib} --no-interactive --bundler=vite`
);
// Create file in public that should be copied to dist
updateFile(`packages/${appName}/public/a/b.txt`, `Hello World!`);
// Additional assets that should be copied to dist
const sharedLib = uniq('sharedLib');
updateJson(join('packages', appName, 'project.json'), (json) => {
json.targets.build.options.assets = [
{
glob: '**/*',
input: `packages/${sharedLib}/src/assets`,
output: 'shared/ui',
},
];
return json;
});
updateFile(`packages/${sharedLib}/src/assets/hello.txt`, 'Hello World!');
// create a css file in node_modules so that it can be imported in a lib
// to test that it works as expected
updateFile(
'node_modules/@nx/next/test-styles.css',
'h1 { background-color: red; }'
);
updateFile(
`packages/${jsLib}/src/lib/${jsLib}.ts`,
`
export function jsLib(): string {
return 'Hello Nx';
};
// testing whether async-await code in Node / Next.js api routes works as expected
export async function jsLibAsync() {
return await Promise.resolve('hell0');
}
`
);
updateFile(
`packages/${buildableLib}/src/lib/${buildableLib}.ts`,
`
export function buildableLib(): string {
return 'Hello Buildable';
};
`
);
const mainPath = `packages/${appName}/pages/index.tsx`;
const content = readFile(mainPath);
updateFile(
`packages/${appName}/pages/api/hello.ts`,
`
import { jsLibAsync } from '@${proj}/${jsLib}';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default async function handler(_: any, res: any) {
const value = await jsLibAsync();
res.send(value);
}
`
);
updateFile(
mainPath,
`
import { jsLib } from '@${proj}/${jsLib}';
import { buildableLib } from '@${proj}/${buildableLib}';
/* eslint-disable */
import dynamic from 'next/dynamic';
const TestComponent = dynamic(
() => import('@${proj}/${nextLib}').then(d => d.${capitalize(
nextLib
)})
);
${content.replace(
`</h2>`,
`</h2>
<div>
{jsLib()}
{buildableLib()}
<TestComponent />
</div>
`
)}`
);
const e2eTestPath = `packages/${appName}-e2e/src/e2e/app.cy.ts`;
const e2eContent = readFile(e2eTestPath);
updateFile(
e2eTestPath,
`
${
e2eContent +
`
it('should successfully call async API route', () => {
cy.request('/api/hello').its('body').should('include', 'hell0');
});
`
}
`
);
await checkApp(appName, {
checkUnitTest: true,
checkLint: true,
checkE2E: isNotWindows(),
checkExport: false,
appsDir: 'packages',
});
// public and shared assets should both be copied to dist
checkFilesExist(
`dist/packages/${appName}/public/a/b.txt`,
`dist/packages/${appName}/public/shared/ui/hello.txt`
);
// Check that compiled next config does not contain bad imports
const nextConfigPath = `dist/packages/${appName}/next.config.js`;
expect(nextConfigPath).not.toContain(`require("../`); // missing relative paths
expect(nextConfigPath).not.toContain(`require("nx/`); // dev-only packages
expect(nextConfigPath).not.toContain(`require("@nx/`); // dev-only packages
// Check that `nx serve <app> --prod` works with previous production build (e.g. `nx build <app>`).
const prodServePort = 4001;
const prodServeProcess = await runCommandUntil(
`run ${appName}:serve --prod --port=${prodServePort}`,
(output) => {
return output.includes(`localhost:${prodServePort}`);
}
);
// Check that the output is self-contained (i.e. can run with its own package.json + node_modules)
const selfContainedPort = 3000;
runCLI(
`generate @nx/workspace:run-commands serve-prod --project ${appName} --cwd=dist/packages/${appName} --command="npx next start --port=${selfContainedPort}"`
);
const selfContainedProcess = await runCommandUntil(
`run ${appName}:serve-prod`,
(output) => {
return output.includes(`localhost:${selfContainedPort}`);
}
);
prodServeProcess.kill();
selfContainedProcess.kill();
await killPort(prodServePort);
await killPort(selfContainedPort);
}, 600_000);
});
|
1,944 | 0 | petrpan-code/nrwl/nx/e2e/next-core | petrpan-code/nrwl/nx/e2e/next-core/src/next-webpack.test.ts | import {
checkFilesExist,
cleanupProject,
newProject,
rmDist,
runCLI,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('Next.js Webpack', () => {
let proj: string;
let originalEnv: string;
beforeEach(() => {
proj = newProject();
originalEnv = process.env.NODE_ENV;
});
afterEach(() => {
process.env.NODE_ENV = originalEnv;
cleanupProject();
});
it('should support custom webpack and run-commands using withNx', async () => {
const appName = uniq('app');
runCLI(
`generate @nx/next:app ${appName} --no-interactive --style=css --appDir=false`
);
updateFile(
`apps/${appName}/next.config.js`,
`
const { withNx } = require('@nx/next');
const nextConfig = {
nx: {
svgr: false,
},
webpack: (config, context) => {
// Make sure SVGR plugin is disabled if nx.svgr === false (see above)
const found = config.module.rules.find(r => {
if (!r.test || !r.test.test('test.svg')) return false;
if (!r.oneOf || !r.oneOf.use) return false;
return r.oneOf.use.some(rr => /svgr/.test(rr.loader));
});
if (found) throw new Error('Found SVGR plugin');
console.log('NODE_ENV is', process.env.NODE_ENV);
return config;
}
};
module.exports = withNx(nextConfig);
`
);
// deleting `NODE_ENV` value, so that it's `undefined`, and not `"test"`
// by the time it reaches the build executor.
// this simulates existing behaviour of running a next.js build executor via Nx
delete process.env.NODE_ENV;
const result = runCLI(`build ${appName}`);
checkFilesExist(`dist/apps/${appName}/next.config.js`);
expect(result).toContain('NODE_ENV is production');
updateFile(
`apps/${appName}/next.config.js`,
`
const { withNx } = require('@nx/next');
// Not including "nx" entry should still work.
const nextConfig = {};
module.exports = withNx(nextConfig);
`
);
rmDist();
runCLI(`build ${appName}`);
checkFilesExist(`dist/apps/${appName}/next.config.js`);
// Make sure withNx works with run-commands.
updateJson(join('apps', appName, 'project.json'), (json) => {
json.targets.build = {
command: 'npx next build',
outputs: [`{projectRoot}/.next`],
options: {
cwd: `apps/${appName}`,
},
};
return json;
});
expect(() => {
runCLI(`build ${appName}`);
}).not.toThrow();
checkFilesExist(`apps/${appName}/.next/build-manifest.json`);
}, 300_000);
});
|
1,945 | 0 | petrpan-code/nrwl/nx/e2e/next-core | petrpan-code/nrwl/nx/e2e/next-core/src/next.test.ts | import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
killPort,
killPorts,
newProject,
readFile,
runCLI,
runCommandUntil,
uniq,
updateFile,
} from '@nx/e2e/utils';
import * as http from 'http';
import { checkApp } from './utils';
describe('Next.js Applications', () => {
let proj: string;
let originalEnv: string;
beforeAll(() => {
proj = newProject();
});
beforeEach(() => {
originalEnv = process.env.NODE_ENV;
});
afterEach(() => {
process.env.NODE_ENV = originalEnv;
});
afterAll(() => cleanupProject());
it('should support generating projects with the new name and root format', () => {
const appName = uniq('app1');
const libName = uniq('@my-org/lib1');
runCLI(
`generate @nx/next:app ${appName} --project-name-and-root-format=as-provided --no-interactive`
);
// check files are generated without the layout directory ("apps/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${appName}/app/page.tsx`);
// check build works
expect(runCLI(`build ${appName}`)).toContain(
`Successfully ran target build for project ${appName}`
);
// check tests pass
const appTestResult = runCLI(`test ${appName}`);
expect(appTestResult).toContain(
`Successfully ran target test for project ${appName}`
);
// assert scoped project names are not supported when --project-name-and-root-format=derived
expect(() =>
runCLI(
`generate @nx/next:lib ${libName} --buildable --project-name-and-root-format=derived --no-interactive`
)
).toThrow();
runCLI(
`generate @nx/next:lib ${libName} --buildable --project-name-and-root-format=as-provided --no-interactive`
);
// check files are generated without the layout directory ("libs/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${libName}/src/index.ts`);
// check build works
expect(runCLI(`build ${libName}`)).toContain(
`Successfully ran target build for project ${libName}`
);
}, 600_000);
it('should build app and .next artifacts at the outputPath if provided by the CLI', () => {
const appName = uniq('app');
runCLI(`generate @nx/next:app ${appName} --no-interactive --style=css`);
runCLI(`build ${appName} --outputPath="dist/foo"`);
checkFilesExist('dist/foo/package.json');
checkFilesExist('dist/foo/next.config.js');
// Next Files
checkFilesExist('dist/foo/.next/package.json');
checkFilesExist('dist/foo/.next/build-manifest.json');
}, 600_000);
// TODO(jack): re-enable this test
xit('should be able to serve with a proxy configuration', async () => {
const appName = uniq('app');
const jsLib = uniq('tslib');
const port = 4200;
runCLI(`generate @nx/next:app ${appName} --appDir=false`);
runCLI(`generate @nx/js:lib ${jsLib} --no-interactive`);
const proxyConf = {
'/external-api': {
target: `http://localhost:${port}`,
pathRewrite: {
'^/external-api/hello': '/api/hello',
},
},
};
updateFile(`apps/${appName}/proxy.conf.json`, JSON.stringify(proxyConf));
updateFile('.env.local', 'NX_CUSTOM_VAR=test value from a file');
updateFile(
`libs/${jsLib}/src/lib/${jsLib}.ts`,
`
export function jsLib(): string {
return process.env.NX_CUSTOM_VAR;
};
`
);
updateFile(
`apps/${appName}/pages/index.tsx`,
`
import React from 'react';
import { jsLib } from '@${proj}/${jsLib}';
export const Index = ({ greeting }: any) => {
return (
<p>{jsLib()}</p>
);
};
export default Index;
`
);
updateFile(
`apps/${appName}/pages/api/hello.js`,
`
export default (_req: any, res: any) => {
res.status(200).send('Welcome');
};
`
);
// serve Next.js
const p = await runCommandUntil(
`run ${appName}:serve --port=${port}`,
(output) => {
return output.indexOf(`[ ready ] on http://localhost:${port}`) > -1;
}
);
const apiData = await getData(port, '/external-api/hello');
const pageData = await getData(port, '/');
expect(apiData).toContain(`Welcome`);
expect(pageData).toContain(`test value from a file`);
await killPort(port);
await killPorts();
}, 300_000);
it('should build in dev mode without errors', async () => {
const appName = uniq('app');
runCLI(
`generate @nx/next:app ${appName} --no-interactive --style=css --appDir=false`
);
checkFilesDoNotExist(`apps/${appName}/.next/build-manifest.json`);
checkFilesDoNotExist(`apps/${appName}/.nx-helpers/with-nx.js`);
expect(() => {
runCLI(`build ${appName} --configuration=development`);
}).not.toThrow();
}, 300_000);
it('should support --js flag', async () => {
const appName = uniq('app');
runCLI(
`generate @nx/next:app ${appName} --no-interactive --js --appDir=false`
);
checkFilesExist(`apps/${appName}/pages/index.js`);
await checkApp(appName, {
checkUnitTest: true,
checkLint: true,
checkE2E: false,
checkExport: false,
});
// Consume a JS lib
const libName = uniq('lib');
runCLI(
`generate @nx/next:lib ${libName} --no-interactive --style=none --js`
);
const mainPath = `apps/${appName}/pages/index.js`;
updateFile(
mainPath,
`import '@${proj}/${libName}';\n` + readFile(mainPath)
);
// Update lib to use css modules
updateFile(
`libs/${libName}/src/lib/${libName}.js`,
`
import styles from './style.module.css';
export function Test() {
return <div className={styles.container}>Hello</div>;
}
`
);
updateFile(
`libs/${libName}/src/lib/style.module.css`,
`
.container {}
`
);
await checkApp(appName, {
checkUnitTest: true,
checkLint: true,
checkE2E: false,
checkExport: false,
});
}, 300_000);
it('should support --no-swc flag', async () => {
const appName = uniq('app');
runCLI(`generate @nx/next:app ${appName} --no-interactive --no-swc`);
// Next.js enables SWC when custom .babelrc is not provided.
checkFilesExist(`apps/${appName}/.babelrc`);
await checkApp(appName, {
checkUnitTest: false,
checkLint: false,
checkE2E: false,
checkExport: false,
});
}, 300_000);
//TODO(caleb): Throwing error Cypress failed to verify that your server is running.
it.skip('should allow using a custom server implementation', async () => {
const appName = uniq('app');
runCLI(
`generate @nx/next:app ${appName} --style=css --no-interactive --custom-server`
);
checkFilesExist(`apps/${appName}/server/main.ts`);
await checkApp(appName, {
checkUnitTest: false,
checkLint: false,
checkE2E: true,
checkExport: false,
});
}, 300_000);
it('should copy relative modules needed by the next.config.js file', async () => {
const appName = uniq('app');
runCLI(`generate @nx/next:app ${appName} --style=css --no-interactive`);
updateFile(`apps/${appName}/redirects.js`, 'module.exports = [];');
updateFile(
`apps/${appName}/nested/headers.js`,
`module.exports = require('./headers-2');`
);
updateFile(`apps/${appName}/nested/headers-2.js`, 'module.exports = [];');
updateFile(`apps/${appName}/next.config.js`, (content) => {
return `const redirects = require('./redirects');\nconst headers = require('./nested/headers.js');\n${content}`;
});
runCLI(`build ${appName}`);
checkFilesExist(`dist/apps/${appName}/redirects.js`);
checkFilesExist(`dist/apps/${appName}/nested/headers.js`);
checkFilesExist(`dist/apps/${appName}/nested/headers-2.js`);
}, 120_000);
it('should support --turbo to enable Turbopack', async () => {
const appName = uniq('app');
runCLI(
`generate @nx/next:app ${appName} --style=css --appDir --no-interactive`
);
const port = 4000;
const selfContainedProcess = await runCommandUntil(
`run ${appName}:serve --port=${port} --turbo`,
(output) => {
return output.includes(`TURBOPACK`);
}
);
selfContainedProcess.kill();
await killPort(port);
await killPorts();
}, 300_000);
});
function getData(port, path = ''): Promise<any> {
return new Promise((resolve, reject) => {
http
.get(`http://localhost:${port}${path}`, (res) => {
expect(res.statusCode).toEqual(200);
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.once('end', () => {
resolve(data);
});
})
.on('error', (err) => reject(err));
});
}
|
1,951 | 0 | petrpan-code/nrwl/nx/e2e/next-extensions | petrpan-code/nrwl/nx/e2e/next-extensions/src/next-component-tests.test.ts | import {
cleanupProject,
createFile,
newProject,
runCLI,
runE2ETests,
uniq,
updateFile,
} from '@nx/e2e/utils';
describe('NextJs Component Testing', () => {
beforeAll(() => {
newProject({
name: uniq('next-ct'),
});
});
afterAll(() => cleanupProject());
it('should test a NextJs app', () => {
const appName = uniq('next-app');
createAppWithCt(appName);
if (runE2ETests()) {
expect(runCLI(`component-test ${appName} --no-watch`)).toContain(
'All specs passed!'
);
}
addTailwindToApp(appName);
if (runE2ETests()) {
expect(runCLI(`component-test ${appName} --no-watch`)).toContain(
'All specs passed!'
);
}
});
it('should test a NextJs app using babel compiler', () => {
const appName = uniq('next-app');
createAppWithCt(appName);
// add bable compiler to app
addBabelSupport(`apps/${appName}`);
if (runE2ETests()) {
expect(runCLI(`component-test ${appName} --no-watch`)).toContain(
'All specs passed!'
);
}
});
it('should test a NextJs lib using babel compiler', async () => {
const libName = uniq('next-lib');
createLibWithCt(libName, false);
// add bable compiler to lib
addBabelSupport(`libs/${libName}`);
if (runE2ETests()) {
expect(runCLI(`component-test ${libName} --no-watch`)).toContain(
'All specs passed!'
);
}
});
it('should test a NextJs lib', async () => {
const libName = uniq('next-lib');
createLibWithCt(libName, false);
if (runE2ETests()) {
expect(runCLI(`component-test ${libName} --no-watch`)).toContain(
'All specs passed!'
);
}
addTailwindToLib(libName);
if (runE2ETests()) {
expect(runCLI(`component-test ${libName} --no-watch`)).toContain(
'All specs passed!'
);
}
});
it('should test a NextJs buildable lib', async () => {
const buildableLibName = uniq('next-buildable-lib');
createLibWithCt(buildableLibName, true);
if (runE2ETests()) {
expect(runCLI(`component-test ${buildableLibName} --no-watch`)).toContain(
'All specs passed!'
);
}
addTailwindToLib(buildableLibName);
if (runE2ETests()) {
expect(runCLI(`component-test ${buildableLibName} --no-watch`)).toContain(
'All specs passed!'
);
}
});
});
function addBabelSupport(path: string) {
updateFile(`${path}/cypress.config.ts`, (content) => {
// apply babel compiler
return content.replace(
'nxComponentTestingPreset(__filename)',
'nxComponentTestingPreset(__filename, {compiler: "babel"})'
);
});
// added needed .babelrc file with defaults
createFile(
`${path}/.babelrc`,
JSON.stringify({ presets: ['next/babel'], plugins: ['istanbul'] })
);
}
function createAppWithCt(appName: string) {
runCLI(`generate @nx/next:app ${appName} --no-interactive --appDir=false`);
runCLI(
`generate @nx/next:component button --project=${appName} --directory=components --flat --no-interactive`
);
createFile(
`apps/${appName}/public/data.json`,
JSON.stringify({ message: 'loaded from app data.json' })
);
updateFile(`apps/${appName}/components/button.tsx`, (content) => {
return `import { useEffect, useState } from 'react';
export interface ButtonProps {
text: string;
}
const data = fetch('/data.json').then((r) => r.json());
export default function Button(props: ButtonProps) {
const [state, setState] = useState<Record<string, any>>();
useEffect(() => {
data.then(setState);
}, []);
return (
<>
{state && <pre>{JSON.stringify(state, null, 2)}</pre>}
<p className="text-blue-600">Button</p>
<button className="text-white bg-black p-4">{props.text}</button>
</>
);
}
`;
});
runCLI(
`generate @nx/next:cypress-component-configuration --project=${appName} --generate-tests --no-interactive`
);
}
function addTailwindToApp(appName: string) {
runCLI(
`generate @nx/react:setup-tailwind --project=${appName} --no-interactive`
);
updateFile(`apps/${appName}/cypress/support/component.ts`, (content) => {
return `${content}
import '../../pages/styles.css'`;
});
updateFile(`apps/${appName}/components/button.cy.tsx`, (content) => {
return `import * as React from 'react';
import Button from './button';
describe(Button.name, () => {
it('renders', () => {
cy.mount(<Button text={'test'} />);
});
it('should apply tailwind', () => {
cy.mount(<Button text={'tailwind'} />);
// should have tailwind styles
cy.get('p').should('have.css', 'color', 'rgb(37, 99, 235)');
});
});
`;
});
}
function createLibWithCt(libName: string, buildable: boolean) {
runCLI(
`generate @nx/next:lib ${libName} --buildable=${buildable} --no-interactive`
);
runCLI(
`generate @nx/next:component button --project=${libName} --flat --export --no-interactive`
);
updateFile(`libs/${libName}/src/lib/button.tsx`, (content) => {
return `import { useEffect, useState } from 'react';
export interface ButtonProps {
text: string
}
export function Button(props: ButtonProps) {
return <button className="text-white bg-black p-4">{props.text}</button>
}
export default Button;
`;
});
runCLI(
`generate @nx/next:cypress-component-configuration --project=${libName} --generate-tests --no-interactive`
);
}
function addTailwindToLib(libName: string) {
createFile(`libs/${libName}/src/lib/styles.css`, ``);
runCLI(
`generate @nx/react:setup-tailwind --project=${libName} --no-interactive`
);
updateFile(`libs/${libName}/src/lib/button.cy.tsx`, (content) => {
return `import * as React from 'react';
import Button from './button';
describe(Button.name, () => {
it('renders', () => {
cy.mount(<Button text={'test'} />);
});
it('should apply tailwind', () => {
cy.mount(<Button text={'tailwind'} />);
// should have tailwind styles
cy.get('button').should('have.css', 'color', 'rgb(255, 255, 255)');
});
});
`;
});
updateFile(`libs/${libName}/cypress/support/styles.ct.css`, (content) => {
return `${content}
@tailwind base;
@tailwind components;
@tailwind utilities;
`;
});
}
|
1,952 | 0 | petrpan-code/nrwl/nx/e2e/next-extensions | petrpan-code/nrwl/nx/e2e/next-extensions/src/next-experimental.test.ts | import {
cleanupProject,
newProject,
runCLI,
uniq,
updateFile,
} from '@nx/e2e/utils';
import { checkApp } from './utils';
describe('Next.js Experimental Features', () => {
let proj: string;
beforeAll(() => (proj = newProject()));
afterAll(() => cleanupProject());
it('should be able to define server actions in workspace libs', async () => {
const appName = uniq('app');
const libName = uniq('lib');
runCLI(`generate @nx/next:app ${appName}`);
runCLI(`generate @nx/next:lib ${libName} --no-interactive`);
// Update the app to test two scenarios:
// 1. Workspace lib with server actions through 'use server' directive
// 2. Workspace with a client component through 'use client' directive
updateFile(
`libs/${libName}/src/lib/action.ts`,
`
'use server';
export async function addItem() {
console.log('adding item');
}
`
);
updateFile(
`libs/${libName}/src/lib/${libName}.tsx`,
`
'use client';
import { addItem } from './action';
export function TestComponent() {
return (
<form action={addItem}>
<button type="submit">Add</button>
</form>
);
};
`
);
updateFile(
`apps/${appName}/app/page.tsx`,
`
import { TestComponent } from '@proj/${libName}';
export default function Home() {
return <TestComponent />;
}
`
);
await checkApp(appName, {
checkUnitTest: false,
checkLint: true,
checkE2E: false,
checkExport: false,
});
}, 300_000);
});
|
1,953 | 0 | petrpan-code/nrwl/nx/e2e/next-extensions | petrpan-code/nrwl/nx/e2e/next-extensions/src/next-storybook.test.ts | import {
checkFilesExist,
cleanupProject,
getPackageManagerCommand,
getSelectedPackageManager,
newProject,
runCLI,
runCommand,
uniq,
} from '@nx/e2e/utils';
const pmc = getPackageManagerCommand({
packageManager: getSelectedPackageManager(),
});
describe('Next.js Storybook', () => {
let proj: string;
beforeAll(() => (proj = newProject({ name: 'proj', packageManager: 'npm' })));
afterAll(() => cleanupProject());
it('should run a Next.js based Storybook setup', async () => {
const appName = uniq('app');
runCLI(`generate @nx/next:app ${appName} --no-interactive`);
runCLI(
`generate @nx/next:component Foo --project=${appName} --no-interactive`
);
runCLI(
`generate @nx/react:storybook-configuration ${appName} --generateStories --no-interactive`
);
// It seems that we need to run install twice for some reason.
// This is only true on CI. On normal repos, it works as expected.
runCommand(pmc.install);
runCLI(`build-storybook ${appName}`);
checkFilesExist(`dist/storybook/${appName}/index.html`);
}, 1_000_000);
});
|
1,954 | 0 | petrpan-code/nrwl/nx/e2e/next-extensions | petrpan-code/nrwl/nx/e2e/next-extensions/src/next-styles.test.ts | import { cleanupProject, newProject, runCLI, uniq } from '@nx/e2e/utils';
import { checkApp } from './utils';
describe('Next.js Styles', () => {
let originalEnv: string;
beforeAll(() => {
newProject();
});
afterAll(() => cleanupProject());
beforeEach(() => {
originalEnv = process.env.NODE_ENV;
});
afterEach(() => {
process.env.NODE_ENV = originalEnv;
});
it('should support different --style options', async () => {
const lessApp = uniq('app');
runCLI(
`generate @nx/next:app ${lessApp} --no-interactive --style=less --appDir=false`
);
await checkApp(lessApp, {
checkUnitTest: false,
checkLint: false,
checkE2E: false,
checkExport: false,
});
const scApp = uniq('app');
runCLI(
`generate @nx/next:app ${scApp} --no-interactive --style=styled-components --appDir=false`
);
await checkApp(scApp, {
checkUnitTest: true,
checkLint: false,
checkE2E: false,
checkExport: false,
});
const scAppWithAppRouter = uniq('app');
runCLI(
`generate @nx/next:app ${scAppWithAppRouter} --no-interactive --style=styled-components --appDir=true`
);
await checkApp(scAppWithAppRouter, {
checkUnitTest: false, // No unit tests for app router
checkLint: false,
checkE2E: false,
checkExport: false,
});
const emotionApp = uniq('app');
runCLI(
`generate @nx/next:app ${emotionApp} --no-interactive --style=@emotion/styled --appDir=false`
);
await checkApp(emotionApp, {
checkUnitTest: true,
checkLint: false,
checkE2E: false,
checkExport: false,
});
}, 600_000);
});
|
1,960 | 0 | petrpan-code/nrwl/nx/e2e/node | petrpan-code/nrwl/nx/e2e/node/src/node-esbuild.test.ts | import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
newProject,
promisifiedTreeKill,
readFile,
runCLI,
runCLIAsync,
runCommandUntil,
setMaxWorkers,
tmpProjPath,
uniq,
updateFile,
} from '@nx/e2e/utils';
import { execSync } from 'child_process';
import { join } from 'path';
describe('Node Applications + esbuild', () => {
beforeEach(() => newProject());
afterEach(() => cleanupProject());
it('should generate an app using esbuild', async () => {
const app = uniq('nodeapp');
runCLI(`generate @nx/node:app ${app} --bundler=esbuild --no-interactive`);
setMaxWorkers(join('apps', app, 'project.json'));
checkFilesDoNotExist(`apps/${app}/webpack.config.js`);
updateFile(`apps/${app}/src/main.ts`, `console.log('Hello World!');`);
const p = await runCommandUntil(`serve ${app} --watch=false`, (output) => {
process.stdout.write(output);
return output.includes(`Hello World!`);
});
checkFilesExist(`dist/apps/${app}/main.js`);
// Check that updating the file won't trigger a rebuild since --watch=false.
updateFile(`apps/${app}/src/main.ts`, `console.log('Bye1');`);
await new Promise((res) => setTimeout(res, 2000));
expect(readFile(`dist/apps/${app}/apps/${app}/src/main.js`)).not.toContain(
`Bye!`
);
await promisifiedTreeKill(p.pid, 'SIGKILL');
}, 300_000);
});
|
1,961 | 0 | petrpan-code/nrwl/nx/e2e/node | petrpan-code/nrwl/nx/e2e/node/src/node-server.test.ts | import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
killPort,
newProject,
promisifiedTreeKill,
readFile,
runCLI,
runCommandUntil,
uniq,
updateFile,
setMaxWorkers,
updateJson,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('Node Applications + webpack', () => {
let proj: string;
beforeEach(() => {
proj = newProject();
});
afterEach(() => cleanupProject());
function addLibImport(appName: string, libName: string, importPath?: string) {
const content = readFile(`apps/${appName}/src/main.ts`);
if (importPath) {
updateFile(
`apps/${appName}/src/main.ts`,
`
import { ${libName} } from '${importPath}';
${content}
console.log(${libName}());
`
);
} else {
updateFile(
`apps/${appName}/src/main.ts`,
`
import { ${libName} } from '@${proj}/${libName}';
${content}
console.log(${libName}());
`
);
}
}
async function runE2eTests(appName: string) {
process.env.PORT = '5000';
const childProcess = await runCommandUntil(`serve ${appName}`, (output) => {
return output.includes('http://localhost:5000');
});
const result = runCLI(`e2e ${appName}-e2e --verbose`);
expect(result).toContain('Setting up...');
expect(result).toContain('Tearing down..');
expect(result).toContain('Successfully ran target e2e');
await promisifiedTreeKill(childProcess.pid, 'SIGKILL');
await killPort(5000);
process.env.PORT = '';
}
it('should generate an app using webpack', async () => {
const testLib1 = uniq('test1');
const testLib2 = uniq('test2');
const expressApp = uniq('expressapp');
const fastifyApp = uniq('fastifyapp');
const koaApp = uniq('koaapp');
const nestApp = uniq('nest');
runCLI(`generate @nx/node:lib ${testLib1}`);
runCLI(`generate @nx/node:lib ${testLib2} --importPath=@acme/test2`);
runCLI(
`generate @nx/node:app ${expressApp} --framework=express --no-interactive`
);
setMaxWorkers(join('apps', expressApp, 'project.json'));
runCLI(
`generate @nx/node:app ${fastifyApp} --framework=fastify --no-interactive`
);
setMaxWorkers(join('apps', fastifyApp, 'project.json'));
runCLI(`generate @nx/node:app ${koaApp} --framework=koa --no-interactive`);
setMaxWorkers(join('apps', koaApp, 'project.json'));
runCLI(
`generate @nx/node:app ${nestApp} --framework=nest --bundler=webpack --no-interactive`
);
setMaxWorkers(join('apps', nestApp, 'project.json'));
// Use esbuild by default
checkFilesDoNotExist(`apps/${expressApp}/webpack.config.js`);
checkFilesDoNotExist(`apps/${fastifyApp}/webpack.config.js`);
checkFilesDoNotExist(`apps/${koaApp}/webpack.config.js`);
// Uses only webpack
checkFilesExist(`apps/${nestApp}/webpack.config.js`);
expect(() => runCLI(`lint ${expressApp}`)).not.toThrow();
expect(() => runCLI(`lint ${fastifyApp}`)).not.toThrow();
expect(() => runCLI(`lint ${koaApp}`)).not.toThrow();
expect(() => runCLI(`lint ${nestApp}`)).not.toThrow();
expect(() => runCLI(`lint ${expressApp}-e2e`)).not.toThrow();
expect(() => runCLI(`lint ${fastifyApp}-e2e`)).not.toThrow();
expect(() => runCLI(`lint ${koaApp}-e2e`)).not.toThrow();
expect(() => runCLI(`lint ${nestApp}-e2e`)).not.toThrow();
// Only Fastify generates with unit tests since it supports them without additional libraries.
expect(() => runCLI(`test ${fastifyApp}`)).not.toThrow();
// https://github.com/nrwl/nx/issues/16601
const nestMainContent = readFile(`apps/${nestApp}/src/main.ts`);
updateFile(
`apps/${nestApp}/src/main.ts`,
`
${nestMainContent}
// Make sure this is not replaced during build time
console.log('env: ' + process.env['NODE_ENV']);
`
);
runCLI(`build ${nestApp}`);
expect(readFile(`dist/apps/${nestApp}/main.js`)).toContain(
`'env: ' + process.env['NODE_ENV']`
);
addLibImport(expressApp, testLib1);
addLibImport(expressApp, testLib2, '@acme/test2');
addLibImport(fastifyApp, testLib1);
addLibImport(fastifyApp, testLib2, '@acme/test2');
addLibImport(koaApp, testLib1);
addLibImport(koaApp, testLib2, '@acme/test2');
addLibImport(nestApp, testLib1);
addLibImport(nestApp, testLib2, '@acme/test2');
await runE2eTests(expressApp);
await runE2eTests(fastifyApp);
await runE2eTests(koaApp);
await runE2eTests(nestApp);
}, 900_000);
it('should generate a Dockerfile', async () => {
const expressApp = uniq('expressapp');
runCLI(
`generate @nx/node:app ${expressApp} --framework=express --docker --no-interactive`
);
setMaxWorkers(join('apps', expressApp, 'project.json'));
checkFilesExist(`apps/${expressApp}/Dockerfile`);
}, 300_000);
it('should support waitUntilTargets for serve target', async () => {
const nodeApp1 = uniq('nodeapp1');
const nodeApp2 = uniq('nodeapp2');
runCLI(
`generate @nx/node:app ${nodeApp1} --framework=none --no-interactive`
);
setMaxWorkers(join('apps', nodeApp1, 'project.json'));
runCLI(
`generate @nx/node:app ${nodeApp2} --framework=none --no-interactive`
);
setMaxWorkers(join('apps', nodeApp2, 'project.json'));
updateJson(join('apps', nodeApp1, 'project.json'), (config) => {
config.targets.serve.options.waitUntilTargets = [`${nodeApp2}:build`];
return config;
});
runCLI(`serve ${nodeApp1} --watch=false`);
checkFilesExist(`dist/apps/${nodeApp1}/main.js`);
checkFilesExist(`dist/apps/${nodeApp2}/main.js`);
}, 300_000);
});
|
1,962 | 0 | petrpan-code/nrwl/nx/e2e/node | petrpan-code/nrwl/nx/e2e/node/src/node-webpack.test.ts | import {
checkFilesExist,
cleanupProject,
newProject,
readFile,
runCLI,
runCLIAsync,
runCommandUntil,
waitUntil,
tmpProjPath,
uniq,
updateFile,
setMaxWorkers,
updateJson,
} from '@nx/e2e/utils';
import { execSync } from 'child_process';
import { join } from 'path';
describe('Node Applications + webpack', () => {
beforeEach(() => newProject());
afterEach(() => cleanupProject());
it('should generate an app using webpack', async () => {
const app = uniq('nodeapp');
runCLI(`generate @nx/node:app ${app} --bundler=webpack --no-interactive`);
setMaxWorkers(join('apps', app, 'project.json'));
checkFilesExist(`apps/${app}/webpack.config.js`);
updateFile(
`apps/${app}/src/main.ts`,
`
function foo(x: string) {
return "foo " + x;
};
console.log(foo("bar"));
`
);
await runCLIAsync(`build ${app}`);
checkFilesExist(`dist/apps/${app}/main.js`);
// no optimization by default
const content = readFile(`dist/apps/${app}/main.js`);
expect(content).toContain('console.log(foo("bar"))');
const result = execSync(`node dist/apps/${app}/main.js`, {
cwd: tmpProjPath(),
}).toString();
expect(result).toMatch(/foo bar/);
await runCLIAsync(`build ${app} --optimization`);
const optimizedContent = readFile(`dist/apps/${app}/main.js`);
expect(optimizedContent).toContain('console.log("foo bar")');
// Test that serve can re-run dependency builds.
const lib = uniq('nodelib');
runCLI(`generate @nx/js:lib ${lib} --bundler=esbuild --no-interactive`);
updateJson(join('apps', app, 'project.json'), (config) => {
// Since we read from lib from dist, we should re-build it when lib changes.
config.targets.build.options.buildLibsFromSource = false;
config.targets.serve.options.runBuildTargetDependencies = true;
return config;
});
updateFile(
`apps/${app}/src/main.ts`,
`
import { ${lib} } from '@proj/${lib}';
console.log('Hello ' + ${lib}());
`
);
const serveProcess = await runCommandUntil(
`serve ${app} --watch --runBuildTargetDependencies`,
(output) => {
return output.includes(`Hello`);
}
);
// Update library source and check that it triggers rebuild.
const terminalOutputs: string[] = [];
serveProcess.stdout.on('data', (chunk) => {
const data = chunk.toString();
terminalOutputs.push(data);
});
updateFile(
`libs/${lib}/src/index.ts`,
`export function ${lib}() { return 'should rebuild lib'; }`
);
await waitUntil(
() => {
return terminalOutputs.some((output) =>
output.includes(`should rebuild lib`)
);
},
{ timeout: 30_000, ms: 200 }
);
serveProcess.kill();
}, 300_000);
});
|
1,963 | 0 | petrpan-code/nrwl/nx/e2e/node | petrpan-code/nrwl/nx/e2e/node/src/node.test.ts | import { stripIndents } from '@angular-devkit/core/src/utils/literals';
import { joinPathFragments } from '@nx/devkit';
import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
createFile,
detectPackageManager,
expectJestTestsToPass,
getPackageManagerCommand,
killPorts,
newProject,
packageInstall,
packageManagerLockFile,
promisifiedTreeKill,
readFile,
runCLI,
runCLIAsync,
runCommand,
runCommandUntil,
tmpProjPath,
uniq,
updateFile,
updateJson,
setMaxWorkers,
} from '@nx/e2e/utils';
import { exec, execSync } from 'child_process';
import * as http from 'http';
import { getLockFileName } from '@nx/js';
import { satisfies } from 'semver';
import { join } from 'path';
function getData(port, path = '/api'): Promise<any> {
return new Promise((resolve) => {
http.get(`http://localhost:${port}${path}`, (res) => {
expect(res.statusCode).toEqual(200);
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.once('end', () => {
try {
resolve(JSON.parse(data));
} catch (e) {
resolve(data);
}
});
});
});
}
describe('Node Applications', () => {
beforeEach(() => newProject());
afterEach(() => cleanupProject());
it('should be able to generate an empty application', async () => {
const nodeapp = uniq('nodeapp');
runCLI(`generate @nx/node:app ${nodeapp} --linter=eslint`);
setMaxWorkers(join('apps', nodeapp, 'project.json'));
const lintResults = runCLI(`lint ${nodeapp}`);
expect(lintResults).toContain('All files pass linting.');
updateFile(`apps/${nodeapp}/src/main.ts`, `console.log('Hello World!');`);
await runCLIAsync(`build ${nodeapp}`);
checkFilesExist(`dist/apps/${nodeapp}/main.js`);
const result = execSync(`node dist/apps/${nodeapp}/main.js`, {
cwd: tmpProjPath(),
}).toString();
expect(result).toContain('Hello World!');
}, 300000);
it('should be able to generate the correct outputFileName in options', async () => {
const nodeapp = uniq('nodeapp');
runCLI(`generate @nx/node:app ${nodeapp} --linter=eslint`);
setMaxWorkers(join('apps', nodeapp, 'project.json'));
updateJson(join('apps', nodeapp, 'project.json'), (config) => {
config.targets.build.options.outputFileName = 'index.js';
return config;
});
await runCLIAsync(`build ${nodeapp}`);
checkFilesExist(`dist/apps/${nodeapp}/index.js`);
}, 300000);
it('should be able to generate an empty application with additional entries', async () => {
const nodeapp = uniq('nodeapp');
runCLI(
`generate @nx/node:app ${nodeapp} --linter=eslint --bundler=webpack`
);
setMaxWorkers(join('apps', nodeapp, 'project.json'));
const lintResults = runCLI(`lint ${nodeapp}`);
expect(lintResults).toContain('All files pass linting.');
updateJson(join('apps', nodeapp, 'project.json'), (config) => {
config.targets.build.options.additionalEntryPoints = [
{
entryName: 'additional-main',
entryPath: `apps/${nodeapp}/src/additional-main.ts`,
},
];
return config;
});
updateFile(
`apps/${nodeapp}/src/additional-main.ts`,
`console.log('Hello Additional World!');`
);
updateFile(
`apps/${nodeapp}/src/main.ts`,
`console.log('Hello World!');
console.log('env: ' + process.env['NODE_ENV']);
`
);
await runCLIAsync(`build ${nodeapp}`);
checkFilesExist(
`dist/apps/${nodeapp}/main.js`,
`dist/apps/${nodeapp}/additional-main.js`
);
const result = execSync(
`NODE_ENV=development && node dist/apps/${nodeapp}/main.js`,
{
cwd: tmpProjPath(),
}
).toString();
expect(result).toContain('Hello World!');
expect(result).toContain('env: development');
const additionalResult = execSync(
`node dist/apps/${nodeapp}/additional-main.js`,
{
cwd: tmpProjPath(),
}
).toString();
expect(additionalResult).toContain('Hello Additional World!');
}, 300_000);
it('should be able to generate an empty application with variable in .env file', async () => {
const originalEnvPort = process.env.PORT;
const port = 3457;
process.env.PORT = `${port}`;
const nodeapp = uniq('nodeapp');
runCLI(
`generate @nx/node:app ${nodeapp} --linter=eslint --bundler=webpack --framework=none`
);
setMaxWorkers(join('apps', nodeapp, 'project.json'));
updateFile('.env', `NX_FOOBAR="test foo bar"`);
updateFile(
`apps/${nodeapp}/src/main.ts`,
`console.log('foobar: ' + process.env['NX_FOOBAR']);`
);
await runCLIAsync(`build ${nodeapp}`);
checkFilesExist(`dist/apps/${nodeapp}/main.js`);
// check serving
const p = await runCommandUntil(
`serve ${nodeapp} --port=${port} --watch=false`,
(output) => {
process.stdout.write(output);
return output.includes(`foobar: test foo bar`);
}
);
try {
await promisifiedTreeKill(p.pid, 'SIGKILL');
await killPorts(port);
} finally {
process.env.port = originalEnvPort;
}
}, 60000);
it('should be able to generate an express application', async () => {
const nodeapp = uniq('nodeapp');
const originalEnvPort = process.env.PORT;
const port = 3456;
process.env.PORT = `${port}`;
runCLI(`generate @nx/express:app ${nodeapp} --linter=eslint`);
setMaxWorkers(join('apps', nodeapp, 'project.json'));
const lintResults = runCLI(`lint ${nodeapp}`);
expect(lintResults).toContain('All files pass linting.');
updateFile(
`apps/${nodeapp}/src/app/test.spec.ts`,
`
describe('test', () => {
it('should work', () => {
expect(true).toEqual(true);
})
})
`
);
const jestResult = runCLI(`test ${nodeapp}`);
expect(jestResult).toContain('Successfully ran target test');
// checking serve
updateFile(`apps/${nodeapp}/src/assets/file.txt`, `Test`);
const p = await runCommandUntil(`serve ${nodeapp}`, (output) =>
output.includes(`Listening at http://localhost:${port}`)
);
let result = await getData(port);
expect(result.message).toMatch(`Welcome to ${nodeapp}!`);
result = await getData(port, '/assets/file.txt');
expect(result).toMatch(`Test`);
try {
await promisifiedTreeKill(p.pid, 'SIGKILL');
await killPorts(port);
} finally {
process.env.port = originalEnvPort;
}
}, 120_000);
xit('should be able to generate a nest application', async () => {
const nestapp = uniq('nestapp');
const port = 3335;
runCLI(`generate @nx/nest:app ${nestapp} --linter=eslint`);
setMaxWorkers(join('apps', nestapp, 'project.json'));
const lintResults = runCLI(`lint ${nestapp}`);
expect(lintResults).toContain('All files pass linting.');
updateFile(`apps/${nestapp}/src/assets/file.txt`, ``);
const jestResult = await runCLIAsync(`test ${nestapp}`);
expect(jestResult.combinedOutput).toContain(
'Test Suites: 2 passed, 2 total'
);
await runCLIAsync(`build ${nestapp}`);
checkFilesExist(
`dist/apps/${nestapp}/main.js`,
`dist/apps/${nestapp}/assets/file.txt`,
`dist/apps/${nestapp}/main.js.map`
);
const server = exec(`node ./dist/apps/${nestapp}/main.js`, {
cwd: tmpProjPath(),
});
expect(server).toBeTruthy();
// checking build
await new Promise((resolve) => {
server.stdout.on('data', async (data) => {
const message = data.toString();
if (message.includes(`Listening at http://localhost:${port}`)) {
const result = await getData(port);
expect(result.message).toEqual(`Welcome to ${nestapp}!`);
server.kill();
resolve(null);
}
});
});
// checking serve
const p = await runCommandUntil(
`serve ${nestapp} --port=${port}`,
(output) => {
process.stdout.write(output);
return output.includes(`Listening at http://localhost:${port}`);
}
);
const result = await getData(port);
expect(result.message).toEqual(`Welcome to ${nestapp}!`);
try {
await promisifiedTreeKill(p.pid, 'SIGKILL');
expect(await killPorts(port)).toBeTruthy();
} catch (err) {
expect(err).toBeFalsy();
}
}, 120000);
it('should be able to run ESM applications', async () => {
const esmapp = uniq('esmapp');
runCLI(
`generate @nrwl/node:app ${esmapp} --linter=eslint --framework=none --bundler=webpack`
);
setMaxWorkers(join('apps', esmapp, 'project.json'));
updateJson(`apps/${esmapp}/tsconfig.app.json`, (config) => {
config.module = 'esnext';
config.target = 'es2020';
return config;
});
updateJson(join('apps', esmapp, 'project.json'), (config) => {
config.targets.build.options.outputFileName = 'main.mjs';
config.targets.build.options.assets = [];
return config;
});
updateFile(
`apps/${esmapp}/webpack.config.js`,
`
const { composePlugins, withNx } = require('@nx/webpack');
module.exports = composePlugins(withNx(), (config) => {
config.experiments = {
...config.experiments,
outputModule: true,
topLevelAwait: true,
};
config.output = {
path: config.output.path,
chunkFormat: 'module',
library: { type: 'module' }
}
return config;
});
`
);
await runCLIAsync(`build ${esmapp}`);
const p = await runCommandUntil(`serve ${esmapp}`, (output) => {
return output.includes('Hello World');
});
p.kill();
}, 300000);
});
describe('Build Node apps', () => {
beforeEach(() => newProject());
afterEach(() => cleanupProject());
it('should generate a package.json with the `--generatePackageJson` flag', async () => {
const scope = newProject();
const packageManager = detectPackageManager(tmpProjPath());
const nestapp = uniq('nestapp');
runCLI(`generate @nx/nest:app ${nestapp} --linter=eslint`);
setMaxWorkers(join('apps', nestapp, 'project.json'));
await runCLIAsync(`build ${nestapp} --generatePackageJson`);
checkFilesExist(`dist/apps/${nestapp}/package.json`);
checkFilesExist(
`dist/apps/${nestapp}/${getLockFileName(
detectPackageManager(tmpProjPath())
)}`
);
const rootPackageJson = JSON.parse(readFile(`package.json`));
const packageJson = JSON.parse(
readFile(`dist/apps/${nestapp}/package.json`)
);
expect(packageJson).toEqual(
expect.objectContaining({
main: 'main.js',
name: expect.any(String),
version: '0.0.1',
})
);
expect(
satisfies(
packageJson.dependencies['@nestjs/common'],
rootPackageJson.dependencies['@nestjs/common']
)
).toBeTruthy();
expect(
satisfies(
packageJson.dependencies['@nestjs/core'],
rootPackageJson.dependencies['@nestjs/core']
)
).toBeTruthy();
expect(
satisfies(
packageJson.dependencies['reflect-metadata'],
rootPackageJson.dependencies['reflect-metadata']
)
).toBeTruthy();
expect(
satisfies(
packageJson.dependencies['rxjs'],
rootPackageJson.dependencies['rxjs']
)
).toBeTruthy();
expect(
satisfies(
packageJson.dependencies['tslib'],
rootPackageJson.dependencies['tslib']
)
).toBeTruthy();
checkFilesExist(
`dist/apps/${nestapp}/${packageManagerLockFile[packageManager]}`
);
runCommand(`${getPackageManagerCommand().ciInstall}`, {
cwd: joinPathFragments(tmpProjPath(), 'dist/apps', nestapp),
});
const nodeapp = uniq('nodeapp');
runCLI(`generate @nx/node:app ${nodeapp} --bundler=webpack`);
setMaxWorkers(join('apps', nodeapp, 'project.json'));
const jslib = uniq('jslib');
runCLI(`generate @nx/js:lib ${jslib} --bundler=tsc`);
updateFile(
`apps/${nodeapp}/src/main.ts`,
`
import { ${jslib} } from '@${scope}/${jslib}';
console.log('Hello World!');
${jslib}();
`
);
const { combinedOutput: nodeCombinedOutput } = await runCLIAsync(
`build ${nodeapp} --generate-package-json`
);
expect(nodeCombinedOutput).not.toMatch(/Graph is not consistent/);
checkFilesExist(`dist/apps/${nodeapp}/package.json`);
checkFilesExist(
`dist/apps/${nodeapp}/${packageManagerLockFile[packageManager]}`
);
const nodeAppPackageJson = JSON.parse(
readFile(`dist/apps/${nodeapp}/package.json`)
);
expect(nodeAppPackageJson['dependencies']['tslib']).toBeTruthy();
runCommand(`${getPackageManagerCommand().ciInstall}`, {
cwd: joinPathFragments(tmpProjPath(), 'dist/apps', nestapp),
});
runCommand(`${getPackageManagerCommand().ciInstall}`, {
cwd: joinPathFragments(tmpProjPath(), 'dist/apps', nodeapp),
});
}, 1_000_000);
it('should remove previous output before building with the --deleteOutputPath option set', async () => {
const appName = uniq('app');
runCLI(`generate @nx/node:app ${appName} --no-interactive`);
setMaxWorkers(join('apps', appName, 'project.json'));
// deleteOutputPath should default to true
createFile(`dist/apps/${appName}/_should_remove.txt`);
createFile(`dist/apps/_should_not_remove.txt`);
checkFilesExist(
`dist/apps/${appName}/_should_remove.txt`,
`dist/apps/_should_not_remove.txt`
);
runCLI(`build ${appName} --outputHashing none`); // no explicit deleteOutputPath option set
checkFilesDoNotExist(`dist/apps/${appName}/_should_remove.txt`);
checkFilesExist(`dist/apps/_should_not_remove.txt`);
// Explicitly set `deleteOutputPath` to true
createFile(`dist/apps/${appName}/_should_remove.txt`);
createFile(`dist/apps/_should_not_remove.txt`);
checkFilesExist(
`dist/apps/${appName}/_should_remove.txt`,
`dist/apps/_should_not_remove.txt`
);
runCLI(`build ${appName} --outputHashing none --deleteOutputPath`);
checkFilesDoNotExist(`dist/apps/${appName}/_should_remove.txt`);
checkFilesExist(`dist/apps/_should_not_remove.txt`);
// Explicitly set `deleteOutputPath` to false
createFile(`dist/apps/${appName}/_should_keep.txt`);
createFile(`dist/apps/_should_keep.txt`);
runCLI(`build ${appName} --deleteOutputPath=false --outputHashing none`);
checkFilesExist(`dist/apps/${appName}/_should_keep.txt`);
checkFilesExist(`dist/apps/_should_keep.txt`);
}, 120000);
it('should support generating projects with the new name and root format', () => {
const appName = uniq('app1');
const libName = uniq('@my-org/lib1');
runCLI(
`generate @nx/node:app ${appName} --project-name-and-root-format=as-provided --no-interactive`
);
// check files are generated without the layout directory ("apps/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${appName}/src/main.ts`);
// check build works
expect(runCLI(`build ${appName}`)).toContain(
`Successfully ran target build for project ${appName}`
);
// check tests pass
const appTestResult = runCLI(`test ${appName}`);
expect(appTestResult).toContain(
`Successfully ran target test for project ${appName}`
);
// assert scoped project names are not supported when --project-name-and-root-format=derived
expect(() =>
runCLI(
`generate @nx/node:lib ${libName} --buildable --project-name-and-root-format=derived --no-interactive`
)
).toThrow();
runCLI(
`generate @nx/node:lib ${libName} --buildable --project-name-and-root-format=as-provided --no-interactive`
);
// check files are generated without the layout directory ("libs/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${libName}/src/index.ts`);
// check build works
expect(runCLI(`build ${libName}`)).toContain(
`Successfully ran target build for project ${libName}`
);
// check tests pass
const libTestResult = runCLI(`test ${libName}`);
expect(libTestResult).toContain(
`Successfully ran target test for project ${libName}`
);
}, 500_000);
describe('NestJS', () => {
it('should have plugin output if specified in `tsPlugins`', async () => {
newProject();
const nestapp = uniq('nestapp');
runCLI(`generate @nx/nest:app ${nestapp} --linter=eslint`);
setMaxWorkers(join('apps', nestapp, 'project.json'));
packageInstall('@nestjs/swagger', undefined, '^7.0.0');
updateJson(join('apps', nestapp, 'project.json'), (config) => {
config.targets.build.options.tsPlugins = ['@nestjs/swagger/plugin'];
return config;
});
updateFile(
`apps/${nestapp}/src/app/foo.dto.ts`,
`
export class FooDto {
foo: string;
bar: number;
}`
);
updateFile(
`apps/${nestapp}/src/app/app.controller.ts`,
`
import { Controller, Get } from '@nestjs/common';
import { FooDto } from './foo.dto';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getData() {
return this.appService.getData();
}
@Get('foo')
getFoo(): Promise<FooDto> {
return Promise.resolve({
foo: 'foo',
bar: 123
})
}
}`
);
await runCLIAsync(`build ${nestapp}`);
const mainJs = readFile(`dist/apps/${nestapp}/main.js`);
expect(mainJs).toContain('FooDto');
expect(mainJs).toContain('_OPENAPI_METADATA_FACTORY');
}, 300000);
});
});
describe('nest libraries', function () {
beforeEach(() => newProject());
it('should be able to generate a nest library', async () => {
const nestlib = uniq('nestlib');
runCLI(`generate @nx/nest:lib ${nestlib}`);
const lintResults = runCLI(`lint ${nestlib}`);
expect(lintResults).toContain('All files pass linting.');
const testResults = runCLI(`test ${nestlib}`);
expect(testResults).toContain(
`Successfully ran target test for project ${nestlib}`
);
}, 60000);
it('should be able to generate a nest library w/ service', async () => {
const nestlib = uniq('nestlib');
runCLI(`generate @nx/nest:lib ${nestlib} --service`);
const lintResults = runCLI(`lint ${nestlib}`);
expect(lintResults).toContain('All files pass linting.');
const jestResult = await runCLIAsync(`test ${nestlib}`);
expect(jestResult.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
}, 200000);
it('should be able to generate a nest library w/ controller', async () => {
const nestlib = uniq('nestlib');
runCLI(`generate @nx/nest:lib ${nestlib} --controller`);
const lintResults = runCLI(`lint ${nestlib}`);
expect(lintResults).toContain('All files pass linting.');
const jestResult = await runCLIAsync(`test ${nestlib}`);
expect(jestResult.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
}, 200000);
it('should be able to generate a nest library w/ controller and service', async () => {
const nestlib = uniq('nestlib');
runCLI(`generate @nx/nest:lib ${nestlib} --controller --service`);
const lintResults = runCLI(`lint ${nestlib}`);
expect(lintResults).toContain('All files pass linting.');
const jestResult = await runCLIAsync(`test ${nestlib}`);
expect(jestResult.combinedOutput).toContain(
'Test Suites: 2 passed, 2 total'
);
}, 200000);
it('should have plugin output if specified in `transformers`', async () => {
newProject();
const nestlib = uniq('nestlib');
runCLI(`generate @nx/nest:lib ${nestlib} --buildable`);
packageInstall('@nestjs/swagger', undefined, '^7.0.0');
updateJson(join('libs', nestlib, 'project.json'), (config) => {
config.targets.build.options.transformers = [
{
name: '@nestjs/swagger/plugin',
options: {
dtoFileNameSuffix: ['.model.ts'],
},
},
];
return config;
});
updateFile(
`libs/${nestlib}/src/lib/foo.model.ts`,
`
export class FooModel {
foo?: string;
bar?: number;
}`
);
await runCLIAsync(`build ${nestlib}`);
const fooModelJs = readFile(`dist/libs/${nestlib}/src/lib/foo.model.js`);
expect(stripIndents`${fooModelJs}`).toContain(
stripIndents`
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FooModel = void 0;
const openapi = require("@nestjs/swagger");
class FooModel {
static _OPENAPI_METADATA_FACTORY() {
return { foo: { required: false, type: () => String }, bar: { required: false, type: () => Number } };
}
}
exports.FooModel = FooModel;
//# sourceMappingURL=foo.model.js.map
`
);
}, 300000);
it('should run default jest tests', async () => {
await expectJestTestsToPass('@nx/node:lib');
}, 100000);
});
|
1,968 | 0 | petrpan-code/nrwl/nx/e2e/nuxt | petrpan-code/nrwl/nx/e2e/nuxt/src/nuxt.test.ts | import {
checkFilesExist,
cleanupProject,
killPorts,
newProject,
runCLI,
uniq,
} from '@nx/e2e/utils';
describe('Nuxt Plugin', () => {
let proj: string;
const app = uniq('app');
beforeAll(() => {
proj = newProject({
unsetProjectNameAndRootFormat: false,
});
runCLI(`generate @nx/nuxt:app ${app} --unitTestRunner=vitest`);
runCLI(
`generate @nx/nuxt:component --directory=${app}/src/components/one --name=one --nameAndDirectoryFormat=as-provided --unitTestRunner=vitest`
);
});
afterAll(() => {
killPorts();
cleanupProject();
});
it('should build application', async () => {
const result = runCLI(`build ${app}`);
expect(result).toContain(
`Successfully ran target build for project ${app}`
);
checkFilesExist(`dist/${app}/.nuxt/nuxt.d.ts`);
checkFilesExist(`dist/${app}/.output/nitro.json`);
});
it('should test application', async () => {
const result = runCLI(`test ${app}`);
expect(result).toContain(`Successfully ran target test for project ${app}`);
});
it('should lint application', async () => {
const result = runCLI(`lint ${app}`);
expect(result).toContain(`Successfully ran target lint for project ${app}`);
});
it('should build storybook for app', () => {
runCLI(
`generate @nx/nuxt:storybook-configuration ${app} --generateStories --no-interactive`
);
runCLI(`run ${app}:build-storybook --verbose`);
checkFilesExist(`dist/storybook/${app}/index.html`);
}, 300_000);
});
|
1,973 | 0 | petrpan-code/nrwl/nx/e2e/nx-init | petrpan-code/nrwl/nx/e2e/nx-init/src/nx-init-angular.test.ts | import { PackageManager } from 'nx/src/utils/package-manager';
import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
getPackageManagerCommand,
getPublishedVersion,
getSelectedPackageManager,
runCLI,
runCommand,
runNgNew,
} from '../../utils';
describe('nx init (Angular CLI)', () => {
let project: string;
let packageManager: PackageManager;
let pmc: ReturnType<typeof getPackageManagerCommand>;
beforeEach(() => {
packageManager = getSelectedPackageManager();
// TODO: solve issues with pnpm and remove this fallback
packageManager = packageManager === 'pnpm' ? 'yarn' : packageManager;
pmc = getPackageManagerCommand({ packageManager });
project = runNgNew(packageManager);
});
afterEach(() => {
cleanupProject();
});
it('should successfully convert an Angular CLI workspace to an Nx standalone workspace', () => {
const output = runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --no-interactive`
);
expect(output).toContain('π Done!');
// angular.json should have been deleted
checkFilesDoNotExist('angular.json');
// check nx config files exist
checkFilesExist('nx.json', 'project.json');
// check build
const coldBuildOutput = runCLI(`build ${project} --outputHashing none`);
expect(coldBuildOutput).toContain(
`> nx run ${project}:build:production --outputHashing none`
);
expect(coldBuildOutput).toContain(
`Successfully ran target build for project ${project}`
);
checkFilesExist(`dist/${project}/browser/main.js`);
// run build again to check is coming from cache
const cachedBuildOutput = runCLI(`build ${project} --outputHashing none`);
expect(cachedBuildOutput).toContain(
`> nx run ${project}:build:production --outputHashing none [local cache]`
);
expect(cachedBuildOutput).toContain('Nx read the output from the cache');
expect(cachedBuildOutput).toContain(
`Successfully ran target build for project ${project}`
);
});
it('should successfully convert an Angular CLI workspace to an Nx integrated workspace', () => {
const output = runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --integrated --no-interactive`
);
expect(output).toContain('π Done!');
// angular.json should have been deleted
checkFilesDoNotExist('angular.json');
// check nx config files exist
checkFilesExist('nx.json', `apps/${project}/project.json`);
// check build
const coldBuildOutput = runCLI(`build ${project} --outputHashing none`);
expect(coldBuildOutput).toContain(
`> nx run ${project}:build:production --outputHashing none`
);
expect(coldBuildOutput).toContain(
`Successfully ran target build for project ${project}`
);
checkFilesExist(`dist/apps/${project}/browser/main.js`);
// run build again to check is coming from cache
const cachedBuildOutput = runCLI(`build ${project} --outputHashing none`);
expect(cachedBuildOutput).toContain(
`> nx run ${project}:build:production --outputHashing none [local cache]`
);
expect(cachedBuildOutput).toContain('Nx read the output from the cache');
expect(cachedBuildOutput).toContain(
`Successfully ran target build for project ${project}`
);
});
});
|
1,974 | 0 | petrpan-code/nrwl/nx/e2e/nx-init | petrpan-code/nrwl/nx/e2e/nx-init/src/nx-init-monorepo.test.ts | import {
createNonNxProjectDirectory,
getPackageManagerCommand,
getPublishedVersion,
getSelectedPackageManager,
runCLI,
runCommand,
updateFile,
} from '@nx/e2e/utils';
describe('nx init (Monorepo)', () => {
const pmc = getPackageManagerCommand({
packageManager: getSelectedPackageManager(),
});
it('should convert to an Nx workspace', () => {
createNonNxProjectDirectory();
runCommand(pmc.install);
updateFile(
'packages/package-a/package.json',
JSON.stringify({
name: 'package-a',
scripts: {
serve: 'some serve',
build: 'echo "build successful"',
test: 'some test',
},
})
);
updateFile(
'packages/package-b/package.json',
JSON.stringify({
name: 'package-b',
scripts: {
lint: 'some lint',
},
})
);
const output = runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --cacheable=build --no-interactive`
);
expect(output).toContain('π Done!');
// check build
const buildOutput = runCLI('build package-a');
expect(buildOutput).toContain('build successful');
// run build again for cache
const cachedBuildOutput = runCLI('build package-a');
expect(cachedBuildOutput).toContain('build successful');
expect(cachedBuildOutput).toContain('Nx read the output from the cache');
});
});
|
1,975 | 0 | petrpan-code/nrwl/nx/e2e/nx-init | petrpan-code/nrwl/nx/e2e/nx-init/src/nx-init-nest.test.ts | import {
e2eCwd,
exists,
getPackageManagerCommand,
getPublishedVersion,
runCLI,
} from '@nx/e2e/utils';
import { execSync } from 'child_process';
import { removeSync } from 'fs-extra';
describe('nx init (for NestCLI)', () => {
const pmc = getPackageManagerCommand({
packageManager: 'npm',
});
const projectName = 'nest-app';
const projectRoot = `${e2eCwd}/${projectName}`;
const cliOptions = { cwd: projectRoot };
afterEach(() => {
removeSync(projectRoot);
});
it('should convert NestCLI application to Nx standalone', () => {
execSync(
`${pmc.runUninstalledPackage} @nestjs/cli new ${projectName} --package-manager=npm`,
{
cwd: e2eCwd,
encoding: 'utf-8',
env: process.env,
stdio: 'pipe',
}
);
const output = execSync(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --cacheable=format --no-interactive`,
{
cwd: projectRoot,
encoding: 'utf-8',
env: process.env,
stdio: 'pipe',
}
);
expect(output).toContain('Enabled computation caching');
// nest-cli.json is removed
expect(exists(`${projectRoot}/nest-cli.json`)).toBeFalsy();
// root nx.json exists
expect(exists(`${projectRoot}/nx.json`)).toBeTruthy();
// root project.json exists
expect(exists(`${projectRoot}/project.json`)).toBeTruthy();
runCLI('build', cliOptions);
expect(
exists(`${projectRoot}/dist/${projectName}/src/main.js`)
).toBeTruthy();
// run build again for cache
const buildOutput = runCLI('build', cliOptions);
expect(buildOutput).toContain('Nx read the output from the cache');
}, 10000);
});
|
1,976 | 0 | petrpan-code/nrwl/nx/e2e/nx-init | petrpan-code/nrwl/nx/e2e/nx-init/src/nx-init-npm-repo.test.ts | import {
cleanupProject,
createNonNxProjectDirectory,
getPackageManagerCommand,
getPublishedVersion,
getSelectedPackageManager,
renameFile,
runCLI,
runCommand,
updateFile,
} from '@nx/e2e/utils';
describe('nx init (NPM repo)', () => {
const pmc = getPackageManagerCommand({
packageManager: getSelectedPackageManager(),
});
it('should work in a regular npm repo', () => {
createNonNxProjectDirectory('regular-repo', false);
updateFile(
'package.json',
JSON.stringify({
name: 'package',
scripts: {
echo: 'echo 123',
},
})
);
runCommand(pmc.install);
const output = runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --cacheable=echo --no-interactive`
);
console.log(output);
expect(output).toContain('Enabled computation caching');
expect(runCLI('echo')).toContain('123');
renameFile('nx.json', 'nx.json.old');
expect(runCLI('echo')).toContain('123');
cleanupProject();
});
it('should support compound scripts', () => {
createNonNxProjectDirectory('regular-repo', false);
updateFile(
'package.json',
JSON.stringify({
name: 'package',
scripts: {
compound: 'echo HELLO && echo COMPOUND',
},
})
);
runCommand(pmc.install);
runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --cacheable=compound --no-interactive`
);
const output = runCommand('npm run compound TEST');
expect(output).toContain('HELLO\n');
expect(output).toContain('COMPOUND TEST');
expect(output).not.toContain('HELLO COMPOUND');
cleanupProject();
});
});
|
1,977 | 0 | petrpan-code/nrwl/nx/e2e/nx-init | petrpan-code/nrwl/nx/e2e/nx-init/src/nx-init-react.test.ts | import {
checkFilesDoNotExist,
checkFilesExist,
getPackageManagerCommand,
getPublishedVersion,
getSelectedPackageManager,
readFile,
readJson,
runCLI,
runCommand,
updateFile,
} from '@nx/e2e/utils';
import { copySync, renameSync } from 'fs-extra';
import { sync as globSync } from 'glob';
import { join } from 'path';
import {
createNonNxProjectDirectory,
tmpProjPath,
updateJson,
} from '../../utils';
const pmc = getPackageManagerCommand({
packageManager: getSelectedPackageManager(),
});
describe('nx init (for React)', () => {
// TODO(@jaysoo): Please investigate why this test is failing
xit('should convert to an integrated workspace with craco (webpack)', () => {
const appName = 'my-app';
createReactApp(appName);
const craToNxOutput = runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --nxCloud=false --integrated --vite=false`
);
expect(craToNxOutput).toContain('π Done!');
const packageJson = readJson('package.json');
expect(packageJson.devDependencies['@nx/jest']).toBeDefined();
expect(packageJson.devDependencies['@nx/vite']).toBeUndefined();
expect(packageJson.devDependencies['@nx/webpack']).toBeDefined();
expect(packageJson.dependencies['redux']).toBeDefined();
expect(packageJson.name).toEqual(appName);
runCLI(`build ${appName}`, {
env: {
// since craco 7.1.0 the NODE_ENV is used, since the tests set it
// to "test" is causes an issue with React Refresh Babel
NODE_ENV: undefined,
},
});
checkFilesExist(`dist/apps/${appName}/index.html`);
});
it('should convert to an integrated workspace with Vite', () => {
// TODO investigate why this is broken
const originalPM = process.env.SELECTED_PM;
process.env.SELECTED_PM = originalPM === 'pnpm' ? 'yarn' : originalPM;
const appName = 'my-app';
createReactApp(appName);
const craToNxOutput = runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --nxCloud=false --integrated`
);
expect(craToNxOutput).toContain('π Done!');
const packageJson = readJson('package.json');
expect(packageJson.devDependencies['@nx/jest']).toBeUndefined();
expect(packageJson.devDependencies['@nx/vite']).toBeDefined();
expect(packageJson.devDependencies['@nx/webpack']).toBeUndefined();
const viteConfig = readFile(`apps/${appName}/vite.config.js`);
expect(viteConfig).toContain('port: 4200'); // default port
runCLI(`build ${appName}`);
checkFilesExist(`dist/apps/${appName}/index.html`);
const unitTestsOutput = runCLI(`test ${appName}`);
expect(unitTestsOutput).toContain('Successfully ran target test');
process.env.SELECTED_PM = originalPM;
});
it('should convert to an integrated workspace with Vite with custom port', () => {
// TODO investigate why this is broken
const originalPM = process.env.SELECTED_PM;
process.env.SELECTED_PM = originalPM === 'pnpm' ? 'yarn' : originalPM;
const appName = 'my-app';
createReactApp(appName);
updateFile(`.env`, `NOT_THE_PORT=8000\nPORT=3000\nSOMETHING_ELSE=whatever`);
runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --nxCloud=false --force --integrated`
);
const viteConfig = readFile(`apps/${appName}/vite.config.js`);
expect(viteConfig).toContain('port: 3000');
const unitTestsOutput = runCLI(`test ${appName}`);
expect(unitTestsOutput).toContain('Successfully ran target test');
process.env.SELECTED_PM = originalPM;
});
it('should convert to a standalone workspace with craco (webpack)', () => {
const appName = 'my-app';
createReactApp(appName);
const craToNxOutput = runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --nxCloud=false --vite=false`
);
expect(craToNxOutput).toContain('π Done!');
runCLI(`build ${appName}`, {
env: {
// since craco 7.1.0 the NODE_ENV is used, since the tests set it
// to "test" is causes an issue with React Refresh Babel
NODE_ENV: undefined,
},
});
checkFilesExist(`dist/${appName}/index.html`);
});
it('should convert to an standalone workspace with Vite', () => {
const appName = 'my-app';
createReactApp(appName);
const craToNxOutput = runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --nxCloud=false --vite`
);
expect(craToNxOutput).toContain('π Done!');
checkFilesDoNotExist(
'libs/.gitkeep',
'tools/tsconfig.tools.json',
'babel.config.json',
'jest.preset.js',
'jest.config.ts'
);
const packageJson = readJson('package.json');
expect(packageJson.devDependencies['@nx/jest']).toBeUndefined();
expect(packageJson.dependencies['redux']).toBeDefined();
expect(packageJson.name).toEqual(appName);
const viteConfig = readFile(`vite.config.js`);
expect(viteConfig).toContain('port: 4200'); // default port
runCLI(`build ${appName}`);
checkFilesExist(`dist/${appName}/index.html`);
const unitTestsOutput = runCLI(`test ${appName}`);
expect(unitTestsOutput).toContain('Successfully ran target test');
});
});
function createReactApp(appName: string) {
const pmc = getPackageManagerCommand({
packageManager: getSelectedPackageManager(),
});
createNonNxProjectDirectory();
const projPath = tmpProjPath();
copySync(join(__dirname, 'files/cra'), projPath);
const filesToRename = globSync(join(projPath, '**/*.txt'));
filesToRename.forEach((f) => {
renameSync(f, f.split('.txt')[0]);
});
updateFile('.gitignore', 'node_modules');
updateJson('package.json', (_) => ({
name: appName,
version: '0.1.0',
private: true,
dependencies: {
'@testing-library/jest-dom': '5.16.5',
'@testing-library/react': '13.4.0',
'@testing-library/user-event': '13.5.0',
react: '^18.2.0',
'react-dom': '^18.2.0',
'react-scripts': '5.0.1',
'web-vitals': '2.1.4',
redux: '^3.6.0',
},
scripts: {
start: 'react-scripts start',
build: 'react-scripts build',
test: 'react-scripts test',
eject: 'react-scripts eject',
},
eslintConfig: {
extends: ['react-app', 'react-app/jest'],
},
browserslist: {
production: ['>0.2%', 'not dead', 'not op_mini all'],
development: [
'last 1 chrome version',
'last 1 firefox version',
'last 1 safari version',
],
},
}));
runCommand(pmc.install);
runCommand('git init');
runCommand('git add .');
runCommand('git commit -m "Init"');
}
|
1,990 | 0 | petrpan-code/nrwl/nx/e2e/nx-misc | petrpan-code/nrwl/nx/e2e/nx-misc/src/extras.test.ts | import { parseJson } from '@nx/devkit';
import {
checkFilesExist,
cleanupProject,
isNotWindows,
newProject,
readJson,
runCLI,
setMaxWorkers,
uniq,
updateFile,
readFile,
updateJson,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('Extra Nx Misc Tests', () => {
beforeAll(() => newProject());
afterAll(() => cleanupProject());
describe('Output Style', () => {
it('should stream output', async () => {
const myapp = 'abcdefghijklmon';
runCLI(`generate @nx/web:app ${myapp}`);
setMaxWorkers(join('apps', myapp, 'project.json'));
updateJson(join('apps', myapp, 'project.json'), (c) => {
c.targets['inner'] = {
command: 'echo inner',
};
c.targets['echo'] = {
executor: 'nx:run-commands',
options: {
commands: ['echo 1', 'echo 2', `nx inner ${myapp}`],
parallel: false,
},
};
return c;
});
const withPrefixes = runCLI(`echo ${myapp} --output-style=stream`).split(
isNotWindows() ? '\n' : '\r\n'
);
expect(withPrefixes).toContain(`${myapp}: 1`);
expect(withPrefixes).toContain(`${myapp}: 2`);
expect(withPrefixes).toContain(`${myapp}: inner`);
const noPrefixes = runCLI(
`echo ${myapp} --output-style=stream-without-prefixes`
);
expect(noPrefixes).not.toContain(`${myapp}: `);
});
});
describe('Nx Plugins', () => {
it('should use plugins defined in nx.json', () => {
const nxJson = readJson('nx.json');
nxJson.plugins = ['./tools/plugin'];
updateFile('nx.json', JSON.stringify(nxJson));
updateFile(
'tools/plugin.js',
`
module.exports = {
processProjectGraph: (graph) => {
const Builder = require('@nx/devkit').ProjectGraphBuilder;
const builder = new Builder(graph);
builder.addNode({
name: 'plugin-node',
type: 'lib',
data: {
root: 'test'
}
});
builder.addNode({
name: 'plugin-node2',
type: 'lib',
data: {
root: 'test2'
}
});
builder.addImplicitDependency(
'plugin-node',
'plugin-node2'
);
return builder.getUpdatedProjectGraph();
}
};
`
);
runCLI('graph --file project-graph.json');
const projectGraphJson = readJson('project-graph.json');
expect(projectGraphJson.graph.nodes['plugin-node']).toBeDefined();
expect(projectGraphJson.graph.nodes['plugin-node2']).toBeDefined();
expect(projectGraphJson.graph.dependencies['plugin-node']).toContainEqual(
{
type: 'implicit',
source: 'plugin-node',
target: 'plugin-node2',
}
);
});
});
describe('Run Commands', () => {
const mylib = uniq('lib');
beforeAll(() => {
runCLI(`generate @nx/js:lib ${mylib}`);
});
it('should not override environment variables already set when setting a custom env file path', async () => {
updateFile(
`.env`,
'SHARED_VAR=shared-root-value\nROOT_ONLY=root-only-value'
);
updateFile(
`apps/${mylib}/.custom.env`,
'SHARED_VAR=shared-nested-value\nNESTED_ONLY=nested-only-value'
);
const envFile = `apps/${mylib}/.custom.env`;
runCLI(
`generate @nx/workspace:run-commands echoEnvVariables --command=echo --envFile=${envFile} --project=${mylib}`
);
const command =
process.platform === 'win32'
? `%SHARED_VAR% %ROOT_ONLY% %NESTED_ONLY%` // Windows
: `$SHARED_VAR $ROOT_ONLY $NESTED_ONLY`;
updateJson(join('libs', mylib, 'project.json'), (config) => {
config.targets.echoEnvVariables.options.command += ` ${command}`;
return config;
});
const result = runCLI(`run ${mylib}:echoEnvVariables`);
expect(result).toContain('shared-root-value');
expect(result).not.toContain('shared-nested-value');
expect(result).toContain('root-only-value');
expect(result).toContain('nested-only-value');
}, 120000);
it('should pass options', async () => {
updateJson(join('libs', mylib, 'project.json'), (config) => {
config.targets.echo = {
command: 'echo --var1={args.var1}',
options: {
var1: 'a',
},
};
return config;
});
const result = runCLI(`run ${mylib}:echo`, { silent: true });
expect(result).toContain('--var1=a');
}, 120000);
it('should interpolate provided arguments', async () => {
const echoTarget = uniq('echo');
updateJson(join('libs', mylib, 'project.json'), (config) => {
config.targets[echoTarget] = {
executor: 'nx:run-commands',
options: {
commands: [
'echo "Arguments:"',
'echo " var1: {args.var1}"',
'echo " var2: {args.var2}"',
'echo " hyphen: {args.var-hyphen}"',
'echo " camel: {args.varCamelCase}"',
'echo ""',
],
},
};
return config;
});
const result = runCLI(
`run ${mylib}:${echoTarget} --var1=a --var2=b --var-hyphen=c --varCamelCase=d`
);
expect(result).toContain('var1: a');
expect(result).toContain('var2: b');
expect(result).toContain('hyphen: c');
expect(result).toContain('camel: d');
const resultArgs = runCLI(
`run ${mylib}:${echoTarget} --args="--var1=a --var2=b --var-hyphen=c --varCamelCase=d"`
);
expect(resultArgs).toContain('var1: a');
expect(resultArgs).toContain('var2: b');
expect(resultArgs).toContain('hyphen: c');
expect(resultArgs).toContain('camel: d');
}, 120000);
it('should fail when a process exits non-zero', async () => {
updateJson(join('libs', mylib, 'project.json'), (config) => {
config.targets.error = {
executor: 'nx:run-commands',
options: {
command: `exit 1`,
},
};
return config;
});
try {
runCLI(`run ${mylib}:error`);
fail('Should error if process errors');
} catch (e) {
expect(e.stderr.toString()).toContain(
'command "exit 1" exited with non-zero status code'
);
}
});
it('run command should not break if output property is missing in options and arguments', async () => {
updateJson(join('libs', mylib, 'project.json'), (config) => {
config.targets.lint.outputs = ['{options.outputFile}'];
return config;
});
expect(() =>
runCLI(`run ${mylib}:lint --format=json`, {
silenceError: true,
})
).not.toThrow();
}, 1000000);
it('should handle caching output directories containing trailing slashes', async () => {
// this test relates to https://github.com/nrwl/nx/issues/10549
// 'cp -a /path/dir/ dest/' operates differently to 'cp -a /path/dir dest/'
// --> which means actual build works but subsequent populate from cache (using cp -a) does not
// --> the fix is to remove trailing slashes to ensure consistent & expected behaviour
const mylib = uniq('lib');
const folder = `dist/libs/${mylib}/some-folder`;
runCLI(`generate @nx/js:lib ${mylib}`);
runCLI(
`generate @nx/workspace:run-commands build --command=echo --outputs=${folder}/ --project=${mylib}`
);
const commands = [
process.platform === 'win32'
? `mkdir ${folder}` // Windows
: `mkdir -p ${folder}`,
`echo dummy > ${folder}/dummy.txt`,
];
updateJson(join('libs', mylib, 'project.json'), (config) => {
delete config.targets.build.options.command;
config.targets.build.options = {
...config.targets.build.options,
parallel: false,
commands: commands,
};
return config;
});
// confirm that it builds correctly
runCLI(`build ${mylib}`);
checkFilesExist(`${folder}/dummy.txt`);
// confirm that it populates correctly from the cache
runCLI(`build ${mylib}`);
checkFilesExist(`${folder}/dummy.txt`);
}, 120000);
});
describe('generate --quiet', () => {
it('should not log tree operations or install tasks', () => {
const output = runCLI('generate @nx/react:app --quiet test-project', {
verbose: false,
});
expect(output).not.toContain('CREATE');
expect(output).not.toContain('Installed');
});
});
describe('Env File', () => {
it('should have the right env', () => {
const appName = uniq('app');
runCLI(
`generate @nx/react:app ${appName} --style=css --bundler=webpack --no-interactive`
);
updateFile(
'.env',
`FIRSTNAME="firstname"
LASTNAME="lastname"
NX_USERNAME=$FIRSTNAME $LASTNAME`
);
updateFile(
`apps/${appName}/src/app/app.tsx`,
`
import NxWelcome from './nx-welcome';
export function App() {
return (
<>
<NxWelcome title={process.env.NX_USERNAME} />
</>
);
}
export default App;
`
);
updateFile(
`apps/${appName}/src/app/app.spec.tsx`,
`import { render } from '@testing-library/react';
import App from './app';
describe('App', () => {
it('should have a greeting as the title', () => {
const { getByText } = render(<App />);
expect(getByText(/Welcome firstname lastname/gi)).toBeTruthy();
});
});
`
);
const unitTestsOutput = runCLI(`test ${appName}`);
expect(unitTestsOutput).toContain('Successfully ran target test');
});
});
describe('task graph inputs', () => {
const readExpandedTaskInputResponse = (): Record<
string,
Record<string, string[]>
> =>
parseJson(
readFile('static/environment.js').match(
/window\.expandedTaskInputsResponse\s*=\s*(.*?);/
)[1]
);
const baseLib = 'lib-base-123';
beforeAll(() => {
runCLI(`generate @nx/js:lib ${baseLib}`);
});
it('should correctly expand default task inputs', () => {
runCLI('graph --file=graph.html');
expect(readExpandedTaskInputResponse()[`${baseLib}:build`])
.toMatchInlineSnapshot(`
{
"external": [
"npm:@nx/js",
"npm:tslib",
],
"general": [
".gitignore",
"nx.json",
],
"lib-base-123": [
"libs/lib-base-123/README.md",
"libs/lib-base-123/package.json",
"libs/lib-base-123/project.json",
"libs/lib-base-123/src/index.ts",
"libs/lib-base-123/src/lib/lib-base-123.ts",
"libs/lib-base-123/tsconfig.json",
"libs/lib-base-123/tsconfig.lib.json",
],
}
`);
});
it('should correctly expand dependent task inputs', () => {
const dependentLib = 'lib-dependent-123';
runCLI(`generate @nx/js:lib ${dependentLib}`);
updateJson(join('libs', baseLib, 'project.json'), (config) => {
config.targets['build'].inputs = ['default', '^default'];
config.implicitDependencies = [dependentLib];
return config;
});
updateJson('nx.json', (json) => {
json.namedInputs = {
...json.namedInputs,
default: ['{projectRoot}/**/*'],
};
return json;
});
runCLI('graph --file=graph.html');
expect(readExpandedTaskInputResponse()[`${baseLib}:build`])
.toMatchInlineSnapshot(`
{
"external": [
"npm:@nx/js",
"npm:tslib",
],
"general": [
".gitignore",
"nx.json",
],
"lib-base-123": [
"libs/lib-base-123/.eslintrc.json",
"libs/lib-base-123/README.md",
"libs/lib-base-123/jest.config.ts",
"libs/lib-base-123/package.json",
"libs/lib-base-123/project.json",
"libs/lib-base-123/src/index.ts",
"libs/lib-base-123/src/lib/lib-base-123.spec.ts",
"libs/lib-base-123/src/lib/lib-base-123.ts",
"libs/lib-base-123/tsconfig.json",
"libs/lib-base-123/tsconfig.lib.json",
"libs/lib-base-123/tsconfig.spec.json",
],
"lib-dependent-123": [
"libs/lib-dependent-123/.eslintrc.json",
"libs/lib-dependent-123/README.md",
"libs/lib-dependent-123/jest.config.ts",
"libs/lib-dependent-123/package.json",
"libs/lib-dependent-123/project.json",
"libs/lib-dependent-123/src/index.ts",
"libs/lib-dependent-123/src/lib/lib-dependent-123.spec.ts",
"libs/lib-dependent-123/src/lib/lib-dependent-123.ts",
"libs/lib-dependent-123/tsconfig.json",
"libs/lib-dependent-123/tsconfig.lib.json",
"libs/lib-dependent-123/tsconfig.spec.json",
],
}
`);
});
});
});
|
1,991 | 0 | petrpan-code/nrwl/nx/e2e/nx-misc | petrpan-code/nrwl/nx/e2e/nx-misc/src/misc.test.ts | import type { NxJsonConfiguration, ProjectConfiguration } from '@nx/devkit';
import {
cleanupProject,
createNonNxProjectDirectory,
e2eCwd,
getPackageManagerCommand,
getPublishedVersion,
isNotWindows,
newProject,
readFile,
readJson,
removeFile,
runCLI,
runCLIAsync,
runCommand,
setMaxWorkers,
tmpProjPath,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { renameSync, writeFileSync } from 'fs';
import { ensureDirSync } from 'fs-extra';
import * as path from 'path';
import { major } from 'semver';
import { join } from 'path';
describe('Nx Commands', () => {
beforeAll(() => newProject());
afterAll(() => cleanupProject());
describe('show', () => {
it('should show the list of projects', async () => {
const app1 = uniq('myapp');
const app2 = uniq('myapp');
expect(
runCLI('show projects').replace(/.*nx show projects( --verbose)?\n/, '')
).toEqual('');
runCLI(`generate @nx/web:app ${app1} --tags e2etag`);
runCLI(`generate @nx/web:app ${app2}`);
setMaxWorkers(join('apps', app1, 'project.json'));
const s = runCLI('show projects').split('\n');
expect(s.length).toEqual(5);
expect(s).toContain(app1);
expect(s).toContain(app2);
expect(s).toContain(`${app1}-e2e`);
expect(s).toContain(`${app2}-e2e`);
const withTag = JSON.parse(runCLI('show projects -p tag:e2etag --json'));
expect(withTag).toEqual([app1]);
const withTargets = JSON.parse(
runCLI('show projects --with-target e2e --json')
);
expect(withTargets).toEqual(
expect.arrayContaining([`${app1}-e2e`, `${app2}-e2e`])
);
expect(withTargets.length).toEqual(2);
});
it('should show detailed project info', () => {
const app = uniq('myapp');
runCLI(`generate @nx/web:app ${app}`);
const project: ProjectConfiguration = JSON.parse(
runCLI(`show project ${app}`)
);
expect(project.targets.build).toBeDefined();
expect(project.targets.lint).toBeDefined();
});
});
describe('report and list', () => {
it(`should report package versions`, async () => {
const reportOutput = runCLI('report');
expect(reportOutput).toEqual(
expect.stringMatching(
new RegExp(`\@nx\/workspace.*:.*${getPublishedVersion()}`)
)
);
expect(reportOutput).toContain('@nx/workspace');
}, 120000);
it(`should list plugins`, async () => {
let listOutput = runCLI('list');
expect(listOutput).toContain('NX Installed plugins');
// just check for some, not all
expect(listOutput).toContain('@nx/workspace');
// temporarily make it look like this isn't installed
renameSync(
tmpProjPath('node_modules/@nx/next'),
tmpProjPath('node_modules/@nx/next_tmp')
);
listOutput = runCLI('list');
expect(listOutput).toContain('NX Also available');
// look for specific plugin
listOutput = runCLI('list @nx/workspace');
expect(listOutput).toContain('Capabilities in @nx/workspace');
// check for schematics
expect(listOutput).toContain('workspace');
expect(listOutput).toContain('library');
// check for builders
expect(listOutput).toContain('run-commands');
listOutput = runCLI('list @nx/angular');
expect(listOutput).toContain('Capabilities in @nx/angular');
expect(listOutput).toContain('library');
expect(listOutput).toContain('component');
// check for builders
expect(listOutput).toContain('package');
// // look for uninstalled core plugin
listOutput = runCLI('list @nx/next');
expect(listOutput).toContain('NX @nx/next is not currently installed');
// look for an unknown plugin
listOutput = runCLI('list @wibble/fish');
expect(listOutput).toContain(
'NX @wibble/fish is not currently installed'
);
// put back the @nx/angular module (or all the other e2e tests after this will fail)
renameSync(
tmpProjPath('node_modules/@nx/next_tmp'),
tmpProjPath('node_modules/@nx/next')
);
}, 120000);
});
describe('format', () => {
const myapp = uniq('myapp');
const mylib = uniq('mylib');
beforeAll(async () => {
runCLI(`generate @nx/web:app ${myapp}`);
setMaxWorkers(join('apps', myapp, 'project.json'));
runCLI(`generate @nx/js:lib ${mylib}`);
});
beforeEach(() => {
updateFile(
`apps/${myapp}/src/main.ts`,
`
const x = 1111;
`
);
updateFile(
`apps/${myapp}/src/app/app.element.spec.ts`,
`
const y = 1111;
`
);
updateFile(
`apps/${myapp}/src/app/app.element.ts`,
`
const z = 1111;
`
);
updateFile(
`libs/${mylib}/index.ts`,
`
const x = 1111;
`
);
updateFile(
`libs/${mylib}/src/${mylib}.spec.ts`,
`
const y = 1111;
`
);
updateFile(
`README.md`,
`
my new readme;
`
);
});
it('should check libs and apps specific files', async () => {
if (isNotWindows()) {
const stdout = runCLI(
`format:check --files="libs/${mylib}/index.ts,package.json" --libs-and-apps`,
{ silenceError: true }
);
expect(stdout).toContain(path.normalize(`libs/${mylib}/index.ts`));
expect(stdout).toContain(
path.normalize(`libs/${mylib}/src/${mylib}.spec.ts`)
);
expect(stdout).not.toContain(path.normalize(`README.md`)); // It will be contained only in case of exception, that we fallback to all
}
}, 90000);
it('should check specific project', async () => {
if (isNotWindows()) {
const stdout = runCLI(`format:check --projects=${myapp}`, {
silenceError: true,
});
expect(stdout).toContain(path.normalize(`apps/${myapp}/src/main.ts`));
expect(stdout).toContain(
path.normalize(`apps/${myapp}/src/app/app.element.ts`)
);
expect(stdout).toContain(
path.normalize(`apps/${myapp}/src/app/app.element.spec.ts`)
);
expect(stdout).not.toContain(path.normalize(`libs/${mylib}/index.ts`));
expect(stdout).not.toContain(
path.normalize(`libs/${mylib}/src/${mylib}.spec.ts`)
);
expect(stdout).not.toContain(path.normalize(`README.md`));
}
}, 90000);
it('should check multiple projects', async () => {
if (isNotWindows()) {
const stdout = runCLI(`format:check --projects=${myapp},${mylib}`, {
silenceError: true,
});
expect(stdout).toContain(path.normalize(`apps/${myapp}/src/main.ts`));
expect(stdout).toContain(
path.normalize(`apps/${myapp}/src/app/app.element.spec.ts`)
);
expect(stdout).toContain(
path.normalize(`apps/${myapp}/src/app/app.element.ts`)
);
expect(stdout).toContain(path.normalize(`libs/${mylib}/index.ts`));
expect(stdout).toContain(
path.normalize(`libs/${mylib}/src/${mylib}.spec.ts`)
);
expect(stdout).not.toContain(path.normalize(`README.md`));
}
}, 90000);
it('should check all', async () => {
if (isNotWindows()) {
const stdout = runCLI(`format:check --all`, { silenceError: true });
expect(stdout).toContain(path.normalize(`apps/${myapp}/src/main.ts`));
expect(stdout).toContain(
path.normalize(`apps/${myapp}/src/app/app.element.spec.ts`)
);
expect(stdout).toContain(
path.normalize(`apps/${myapp}/src/app/app.element.ts`)
);
expect(stdout).toContain(path.normalize(`libs/${mylib}/index.ts`));
expect(stdout).toContain(
path.normalize(`libs/${mylib}/src/${mylib}.spec.ts`)
);
expect(stdout).toContain(path.normalize(`README.md`));
}
}, 90000);
it('should throw error if passing both projects and --all param', async () => {
if (isNotWindows()) {
const { stderr } = await runCLIAsync(
`format:check --projects=${myapp},${mylib} --all`,
{
silenceError: true,
}
);
expect(stderr).toContain(
'Arguments all and projects are mutually exclusive'
);
}
}, 90000);
it('should reformat the code', async () => {
if (isNotWindows()) {
runCLI(
`format:write --files="apps/${myapp}/src/app/app.element.spec.ts,apps/${myapp}/src/app/app.element.ts"`
);
const stdout = runCLI('format:check --all', { silenceError: true });
expect(stdout).toContain(path.normalize(`apps/${myapp}/src/main.ts`));
expect(stdout).not.toContain(
path.normalize(`apps/${myapp}/src/app/app.element.spec.ts`)
);
expect(stdout).not.toContain(
path.normalize(`apps/${myapp}/src/app/app.element.ts`)
);
runCLI('format:write --all');
expect(runCLI('format:check --all')).not.toContain(
path.normalize(`apps/${myapp}/src/main.ts`)
);
}
}, 300000);
});
});
// TODO(colum): Change the fetcher to allow incremental migrations over multiple versions, allowing for beforeAll
describe('migrate', () => {
beforeEach(() => {
newProject();
updateFile(
`./node_modules/migrate-parent-package/package.json`,
JSON.stringify({
version: '1.0.0',
name: 'migrate-parent-package',
'nx-migrations': './migrations.json',
})
);
updateFile(
`./node_modules/migrate-parent-package/migrations.json`,
JSON.stringify({
schematics: {
run11: {
version: '1.1.0',
description: '1.1.0',
factory: './run11',
},
},
generators: {
run20: {
version: '2.0.0',
description: '2.0.0',
implementation: './run20',
},
},
})
);
updateFile(
`./node_modules/migrate-parent-package/run11.js`,
`
var angular_devkit_core1 = require("@angular-devkit/core");
exports.default = function default_1() {
return function(host) {
host.create('file-11', 'content11')
}
}
`
);
updateFile(
`./node_modules/migrate-parent-package/run20.js`,
`
exports.default = function (host) {
host.write('file-20', 'content20')
}
`
);
updateFile(
`./node_modules/migrate-child-package/package.json`,
JSON.stringify({
name: 'migrate-child-package',
version: '1.0.0',
})
);
updateFile(
'./node_modules/nx/src/command-line/migrate/migrate.js',
(content) => {
const start = content.indexOf('// testing-fetch-start');
const end = content.indexOf('// testing-fetch-end');
const before = content.substring(0, start);
const after = content.substring(end);
const newFetch = `
function createFetcher(logger) {
return function fetch(packageName) {
if (packageName === 'migrate-parent-package') {
return Promise.resolve({
version: '2.0.0',
generators: {
'run11': {
version: '1.1.0'
},
'run20': {
version: '2.0.0',
cli: 'nx'
}
},
packageJsonUpdates: {
'run-11': {version: '1.1.0', packages: {
'migrate-child-package': {version: '9.0.0', alwaysAddToPackageJson: true},
'migrate-child-package-2': {version: '9.0.0', alwaysAddToPackageJson: false},
'migrate-child-package-3': {version: '9.0.0', addToPackageJson: false},
'migrate-child-package-4': {version: '9.0.0', addToPackageJson: 'dependencies'},
'migrate-child-package-5': {version: '9.0.0', addToPackageJson: 'devDependencies'},
}},
}
});
} else {
return Promise.resolve({version: '9.0.0'});
}
}
}
`;
return `${before}${newFetch}${after}`;
}
);
});
it('should run migrations', () => {
updateJson('nx.json', (j: NxJsonConfiguration) => {
j.installation = {
version: getPublishedVersion(),
plugins: {
'migrate-child-package': '1.0.0',
},
};
return j;
});
runCLI(
'migrate [email protected] --from="[email protected]"',
{
env: {
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
},
}
);
// updates package.json
const packageJson = readJson(`package.json`);
expect(packageJson.dependencies['migrate-child-package']).toEqual('9.0.0');
expect(
packageJson.dependencies['migrate-child-package-2']
).not.toBeDefined();
expect(
packageJson.dependencies['migrate-child-package-3']
).not.toBeDefined();
expect(packageJson.dependencies['migrate-child-package-4']).toEqual(
'9.0.0'
);
expect(packageJson.devDependencies['migrate-child-package-5']).toEqual(
'9.0.0'
);
const nxJson: NxJsonConfiguration = readJson(`nx.json`);
expect(nxJson.installation.plugins['migrate-child-package']).toEqual(
'9.0.0'
);
// should keep new line on package
const packageContent = readFile('package.json');
expect(packageContent.charCodeAt(packageContent.length - 1)).toEqual(10);
// creates migrations.json
const migrationsJson = readJson(`migrations.json`);
expect(migrationsJson).toEqual({
migrations: [
{
package: 'migrate-parent-package',
version: '1.1.0',
name: 'run11',
},
{
package: 'migrate-parent-package',
version: '2.0.0',
name: 'run20',
cli: 'nx',
},
],
});
// runs migrations
runCLI('migrate --run-migrations=migrations.json', {
env: {
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
},
});
expect(readFile('file-11')).toEqual('content11');
expect(readFile('file-20')).toEqual('content20');
});
it('should run migrations and create individual git commits when createCommits is enabled', () => {
runCLI(
'migrate [email protected] --from="[email protected]"',
{
env: {
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
},
}
);
// runs migrations with createCommits enabled
runCLI('migrate --run-migrations=migrations.json --create-commits', {
env: {
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
},
});
const recentCommits = runCommand('git --no-pager log --oneline -n 10');
expect(recentCommits).toContain('chore: [nx migration] run11');
expect(recentCommits).toContain('chore: [nx migration] run20');
});
it('should run migrations and create individual git commits using a provided custom commit prefix', () => {
// Windows has shell escaping issues so this test would always fail
if (isNotWindows()) {
runCLI(
'migrate [email protected] --from="[email protected]"',
{
env: {
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
},
}
);
// runs migrations with createCommits enabled and custom commit-prefix (NOTE: the extra quotes are needed here to avoid shell escaping issues)
runCLI(
`migrate --run-migrations=migrations.json --create-commits --commit-prefix="'chore(core): AUTOMATED - '"`,
{
env: {
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
},
}
);
const recentCommits = runCommand('git --no-pager log --oneline -n 10');
expect(recentCommits).toContain('chore(core): AUTOMATED - run11');
expect(recentCommits).toContain('chore(core): AUTOMATED - run20');
}
});
it('should fail if a custom commit prefix is provided when --create-commits is not enabled', () => {
runCLI(
'migrate [email protected] --from="[email protected]"',
{
env: {
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
},
}
);
// Invalid: runs migrations with a custom commit-prefix but without enabling --create-commits
const output = runCLI(
`migrate --run-migrations=migrations.json --commit-prefix CUSTOM_PREFIX`,
{
env: {
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
},
silenceError: true,
}
);
expect(output).toContain(
`Error: Providing a custom commit prefix requires --create-commits to be enabled`
);
});
it('should fail if no migrations are present', () => {
removeFile(`./migrations.json`);
// Invalid: runs migrations with a custom commit-prefix but without enabling --create-commits
const output = runCLI(`migrate --run-migrations`, {
env: {
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
},
silenceError: true,
});
expect(output).toContain(
`File 'migrations.json' doesn't exist, can't run migrations. Use flag --if-exists to run migrations only if the file exists`
);
});
it('should not run migrations if no migrations are present and flag --if-exists is used', () => {
removeFile(`./migrations.json`);
// Invalid: runs migrations with a custom commit-prefix but without enabling --create-commits
const output = runCLI(`migrate --run-migrations --if-exists`, {
env: {
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
},
silenceError: true,
});
expect(output).toContain(`Migrations file 'migrations.json' doesn't exist`);
});
});
describe('global installation', () => {
// Additionally, installing Nx under e2eCwd like this still acts like a global install,
// but is easier to cleanup and doesn't mess with the users PC if running tests locally.
const globalsPath = path.join(e2eCwd, 'globals', 'node_modules', '.bin');
let oldPath: string;
beforeAll(() => {
ensureDirSync(globalsPath);
writeFileSync(
path.join(path.dirname(path.dirname(globalsPath)), 'package.json'),
JSON.stringify(
{
dependencies: {
nx: getPublishedVersion(),
},
},
null,
2
)
);
runCommand(getPackageManagerCommand().install, {
cwd: path.join(e2eCwd, 'globals'),
});
// Update process.path to have access to modules installed in e2ecwd/node_modules/.bin,
// this lets commands run things like `nx`. We put it at the beginning so they are found first.
oldPath = process.env.PATH;
process.env.PATH = globalsPath + path.delimiter + process.env.PATH;
});
afterAll(() => {
process.env.PATH = oldPath;
});
describe('inside nx directory', () => {
beforeAll(() => {
newProject();
});
it('should invoke Nx commands from local repo', () => {
const nxJsContents = readFile('node_modules/nx/bin/nx.js');
updateFile('node_modules/nx/bin/nx.js', `console.log('local install');`);
let output: string;
expect(() => {
output = runCommand(`nx show projects`);
}).not.toThrow();
expect(output).toContain('local install');
updateFile('node_modules/nx/bin/nx.js', nxJsContents);
});
it('should warn if local Nx has higher major version', () => {
const packageJsonContents = readFile('node_modules/nx/package.json');
updateJson('node_modules/nx/package.json', (json) => {
json.version = `${major(getPublishedVersion()) + 2}.0.0`;
return json;
});
let output: string;
expect(() => {
output = runCommand(`nx show projects`);
}).not.toThrow();
expect(output).toContain('Its time to update Nx');
updateFile('node_modules/nx/package.json', packageJsonContents);
});
it('--version should display global installs version', () => {
const packageJsonContents = readFile('node_modules/nx/package.json');
const localVersion = `${major(getPublishedVersion()) + 2}.0.0`;
updateJson('node_modules/nx/package.json', (json) => {
json.version = localVersion;
return json;
});
let output: string;
expect(() => {
output = runCommand(`nx --version`);
}).not.toThrow();
expect(output).toContain(`- Local: v${localVersion}`);
expect(output).toContain(`- Global: v${getPublishedVersion()}`);
updateFile('node_modules/nx/package.json', packageJsonContents);
});
it('report should display global installs version', () => {
const packageJsonContents = readFile('node_modules/nx/package.json');
const localVersion = `${major(getPublishedVersion()) + 2}.0.0`;
updateJson('node_modules/nx/package.json', (json) => {
json.version = localVersion;
return json;
});
let output: string;
expect(() => {
output = runCommand(`nx report`);
}).not.toThrow();
expect(output).toEqual(
expect.stringMatching(new RegExp(`nx.*:.*${localVersion}`))
);
expect(output).toEqual(
expect.stringMatching(
new RegExp(`nx \\(global\\).*:.*${getPublishedVersion()}`)
)
);
updateFile('node_modules/nx/package.json', packageJsonContents);
});
});
describe('non-nx directory', () => {
beforeAll(() => {
createNonNxProjectDirectory();
});
it('--version should report global version and local not found', () => {
let output: string;
expect(() => {
output = runCommand(`nx --version`);
}).not.toThrow();
expect(output).toContain(`- Local: Not found`);
expect(output).toContain(`- Global: v${getPublishedVersion()}`);
});
it('graph should work in npm workspaces repo', () => {
expect(() => {
runCommand(`nx graph --file graph.json`);
}).not.toThrow();
const { graph } = readJson('graph.json');
expect(graph).toHaveProperty('nodes');
});
});
});
|
1,992 | 0 | petrpan-code/nrwl/nx/e2e/nx-misc | petrpan-code/nrwl/nx/e2e/nx-misc/src/nxw.test.ts | import type { NxJsonConfiguration } from '@nx/devkit';
import {
newWrappedNxWorkspace,
updateFile,
updateJson,
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
getPublishedVersion,
uniq,
readJson,
readFile,
} from '@nx/e2e/utils';
import { bold } from 'chalk';
describe('nx wrapper / .nx installation', () => {
let runNxWrapper: ReturnType<typeof newWrappedNxWorkspace>;
beforeAll(() => {
runNxWrapper = newWrappedNxWorkspace();
});
afterAll(() => {
cleanupProject({
skipReset: true,
});
});
it('should support running targets in a repo with .nx', () => {
updateFile(
'projects/a/project.json',
JSON.stringify({
name: 'a',
targets: {
echo: {
command: `echo 'Hello from A'`,
},
},
})
);
updateJson<NxJsonConfiguration>('nx.json', (json) => {
json.targetDefaults.echo = { cache: true };
json.installation.plugins = {
'@nx/js': getPublishedVersion(),
};
return json;
});
expect(runNxWrapper('echo a')).toContain('Hello from A');
expect(runNxWrapper('echo a')).toContain(
'Nx read the output from the cache instead of running the command for 1 out of 1 tasks'
);
assertNoRootPackages();
expect(() =>
checkFilesExist(
'.nx/installation/package.json',
'.nx/installation/package-lock.json',
'.nx/cache/terminalOutputs'
)
).not.toThrow();
});
it('should work with nx report', () => {
const output = runNxWrapper('report');
expect(output).toMatch(new RegExp(`nx.*:.*${getPublishedVersion()}`));
expect(output).toMatch(new RegExp(`@nx/js.*:.*${getPublishedVersion()}`));
expect(output).not.toContain('@nx/express');
});
it('should work with nx list', () => {
let output = runNxWrapper('list');
const lines = output.split('\n');
const installedPluginStart = lines.findIndex((l) =>
l.includes('Installed plugins')
);
const installedPluginEnd = lines.findIndex((l) =>
l.includes('Also available')
);
const installedPluginLines = lines.slice(
installedPluginStart + 1,
installedPluginEnd
);
expect(installedPluginLines.some((x) => x.includes(`${bold('nx')}`)));
expect(installedPluginLines.some((x) => x.includes(`${bold('@nx/js')}`)));
output = runNxWrapper('list @nx/js');
expect(output).toContain('Capabilities in @nx/js');
});
it('should work with basic generators', () => {
updateJson<NxJsonConfiguration>('nx.json', (j) => {
j.installation.plugins ??= {};
j.installation.plugins['@nx/workspace'] = getPublishedVersion();
return j;
});
expect(() => runNxWrapper(`g npm-package ${uniq('pkg')}`)).not.toThrow();
expect(() => checkFilesExist());
});
it('should work with migrate', () => {
updateFile(
`.nx/installation/node_modules/migrate-parent-package/package.json`,
JSON.stringify({
version: '1.0.0',
name: 'migrate-parent-package',
'nx-migrations': './migrations.json',
})
);
updateFile(
`.nx/installation/node_modules/migrate-parent-package/migrations.json`,
JSON.stringify({
generators: {
run20: {
version: '2.0.0',
description: '2.0.0',
implementation: './run20',
},
},
})
);
updateFile(
`.nx/installation/node_modules/migrate-parent-package/run20.js`,
`
exports.default = function (host) {
host.write('file-20', 'content20')
}
`
);
updateFile(
`.nx/installation/node_modules/migrate-child-package/package.json`,
JSON.stringify({
name: 'migrate-child-package',
version: '1.0.0',
})
);
/**
* Patches migration fetcher to load in migrations that we are using to test.
*/
updateFile(
'.nx/installation/node_modules/nx/src/command-line/migrate/migrate.js',
(content) => {
const start = content.indexOf('// testing-fetch-start');
const end = content.indexOf('// testing-fetch-end');
const before = content.substring(0, start);
const after = content.substring(end);
const newFetch = `
function createFetcher(logger) {
return function fetch(packageName) {
if (packageName === 'migrate-parent-package') {
return Promise.resolve({
version: '2.0.0',
generators: {
'run20': {
version: '2.0.0',
cli: 'nx'
}
},
packageJsonUpdates: {
'run-11': {version: '1.1.0', packages: {
'migrate-child-package': {version: '9.0.0', alwaysAddToPackageJson: false},
}},
}
});
} else {
return Promise.resolve({version: '9.0.0'});
}
}
}
`;
return `${before}${newFetch}${after}`;
}
);
updateJson('nx.json', (j: NxJsonConfiguration) => {
j.installation = {
version: getPublishedVersion(),
plugins: {
'migrate-child-package': '1.0.0',
},
};
return j;
});
runNxWrapper(
'migrate [email protected] --from="[email protected]"',
{
env: {
...process.env,
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
NX_WRAPPER_SKIP_INSTALL: 'true',
},
}
);
const nxJson: NxJsonConfiguration = readJson(`nx.json`);
expect(nxJson.installation.plugins['migrate-child-package']).toEqual(
'9.0.0'
);
// creates migrations.json
const migrationsJson = readJson(`migrations.json`);
expect(migrationsJson).toEqual({
migrations: [
{
package: 'migrate-parent-package',
version: '2.0.0',
name: 'run20',
cli: 'nx',
},
],
});
// runs migrations
runNxWrapper('migrate --run-migrations=migrations.json', {
env: {
...process.env,
NX_MIGRATE_SKIP_INSTALL: 'true',
NX_MIGRATE_USE_LOCAL: 'true',
NX_WRAPPER_SKIP_INSTALL: 'true',
},
});
expect(readFile('file-20')).toEqual('content20');
});
});
function assertNoRootPackages() {
expect(() =>
checkFilesDoNotExist(
'node_modules',
'package.json',
'package-lock.json',
'yarn-lock.json',
'pnpm-lock.yaml'
)
).not.toThrow();
}
|
1,993 | 0 | petrpan-code/nrwl/nx/e2e/nx-misc | petrpan-code/nrwl/nx/e2e/nx-misc/src/watch.test.ts | import {
cleanupProject,
newProject,
runCLI,
uniq,
tmpProjPath,
getStrippedEnvironmentVariables,
updateJson,
isVerboseE2ERun,
readFile,
} from '@nx/e2e/utils';
import { spawn } from 'child_process';
import { join } from 'path';
import { writeFileSync, mkdtempSync } from 'fs';
import { tmpdir } from 'os';
let cacheDirectory = mkdtempSync(join(tmpdir(), 'daemon'));
console.log('cache directory', cacheDirectory);
async function writeFileForWatcher(path: string, content: string) {
const e2ePath = join(tmpProjPath(), path);
console.log(`writing to: ${e2ePath}`);
writeFileSync(e2ePath, content);
await wait(10);
}
describe('Nx Watch', () => {
let proj1 = uniq('proj1');
let proj2 = uniq('proj2');
let proj3 = uniq('proj3');
beforeAll(() => {
newProject();
runCLI(`generate @nx/js:lib ${proj1}`);
runCLI(`generate @nx/js:lib ${proj2}`);
runCLI(`generate @nx/js:lib ${proj3}`);
runCLI('daemon --start', {
env: {
NX_DAEMON: 'true',
NX_NATIVE_LOGGING: 'nx',
NX_PROJECT_GRAPH_CACHE_DIRECTORY: cacheDirectory,
},
});
});
afterEach(() => {
let daemonLog = readFile(join(cacheDirectory, 'd/daemon.log'));
const testName = expect.getState().currentTestName;
console.log(`${testName} daemon log: \n${daemonLog}`);
runCLI('reset');
});
afterAll(() => cleanupProject());
it('should watch for project changes', async () => {
const getOutput = await runWatch(
`--projects=${proj1} -- echo \\$NX_PROJECT_NAME`
);
await writeFileForWatcher(`libs/${proj1}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj2}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj1}/newfile2.txt`, 'content');
await writeFileForWatcher(`libs/${proj3}/newfile2.txt`, 'content');
await writeFileForWatcher(`newfile2.txt`, 'content');
expect(await getOutput()).toEqual([proj1]);
}, 50000);
it('should watch for all projects and output the project name', async () => {
const getOutput = await runWatch(`--all -- echo \\$NX_PROJECT_NAME`);
await writeFileForWatcher(`libs/${proj1}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj2}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj1}/newfile2.txt`, 'content');
await writeFileForWatcher(`libs/${proj3}/newfile2.txt`, 'content');
await writeFileForWatcher(`newfile2.txt`, 'content');
let content = await getOutput();
let results = content.sort();
expect(results).toEqual([proj1, proj2, proj3]);
}, 50000);
it('should watch for all project changes and output the file name changes', async () => {
const getOutput = await runWatch(`--all -- echo \\$NX_FILE_CHANGES`);
await writeFileForWatcher(`libs/${proj1}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj2}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj1}/newfile2.txt`, 'content');
await writeFileForWatcher(`newfile2.txt`, 'content');
let output = (await getOutput())[0];
let results = output.split(' ').sort();
expect(results).toEqual([
`libs/${proj1}/newfile.txt`,
`libs/${proj1}/newfile2.txt`,
`libs/${proj2}/newfile.txt`,
]);
}, 50000);
it('should watch for global workspace file changes', async () => {
const getOutput = await runWatch(
`--all --includeGlobalWorkspaceFiles -- echo \\$NX_FILE_CHANGES`
);
await writeFileForWatcher(`libs/${proj1}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj2}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj1}/newfile2.txt`, 'content');
await writeFileForWatcher(`newfile2.txt`, 'content');
let output = (await getOutput())[0];
let results = output.split(' ').sort();
expect(results).toEqual([
`libs/${proj1}/newfile.txt`,
`libs/${proj1}/newfile2.txt`,
`libs/${proj2}/newfile.txt`,
'newfile2.txt',
]);
}, 50000);
it('should watch selected projects only', async () => {
const getOutput = await runWatch(
`--projects=${proj1},${proj3} -- echo \\$NX_PROJECT_NAME`
);
await writeFileForWatcher(`libs/${proj1}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj2}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj1}/newfile2.txt`, 'content');
await writeFileForWatcher(`libs/${proj3}/newfile2.txt`, 'content');
await writeFileForWatcher(`newfile2.txt`, 'content');
let output = await getOutput();
let results = output.sort();
expect(results).toEqual([proj1, proj3]);
}, 50000);
it('should watch projects including their dependencies', async () => {
updateJson(`libs/${proj3}/project.json`, (json) => {
json.implicitDependencies = [proj1];
return json;
});
const getOutput = await runWatch(
`--projects=${proj3} --includeDependentProjects -- echo \\$NX_PROJECT_NAME`
);
await writeFileForWatcher(`libs/${proj1}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj2}/newfile.txt`, 'content');
await writeFileForWatcher(`libs/${proj1}/newfile2.txt`, 'content');
await writeFileForWatcher(`libs/${proj3}/newfile2.txt`, 'content');
await writeFileForWatcher(`newfile2.txt`, 'content');
let output = await getOutput();
let results = output.sort();
expect(results).toEqual([proj1, proj3]);
}, 50000);
});
async function wait(timeout = 200) {
return new Promise<void>((res) => {
setTimeout(() => {
res();
}, timeout);
});
}
async function runWatch(command: string) {
const runCommand = `npx -c 'nx watch --verbose ${command}'`;
isVerboseE2ERun() && console.log(runCommand);
return new Promise<(timeout?: number) => Promise<string[]>>((resolve) => {
const p = spawn(runCommand, {
cwd: tmpProjPath(),
env: {
CI: 'true',
...getStrippedEnvironmentVariables(),
FORCE_COLOR: 'false',
},
shell: true,
stdio: 'pipe',
});
let output = '';
p.stdout?.on('data', (data) => {
output += data;
const s = data.toString().trim();
isVerboseE2ERun() && console.log(s);
if (s.includes('watch process waiting')) {
resolve(async (timeout = 6000) => {
await wait(timeout);
p.kill();
return output
.split('\n')
.filter((line) => line.length > 0 && !line.includes('NX'));
});
}
});
});
}
|
1,994 | 0 | petrpan-code/nrwl/nx/e2e/nx-misc | petrpan-code/nrwl/nx/e2e/nx-misc/src/workspace.test.ts | import {
checkFilesExist,
newProject,
readJson,
cleanupProject,
runCLI,
uniq,
updateFile,
readFile,
exists,
tmpProjPath,
getPackageManagerCommand,
getSelectedPackageManager,
runCommand,
} from '@nx/e2e/utils';
import { join } from 'path';
let proj: string;
describe('@nx/workspace:convert-to-monorepo', () => {
beforeEach(() => {
proj = newProject();
});
afterEach(() => cleanupProject());
// TODO: troubleshoot and reenable this test
xit('should convert a standalone project to a monorepo', async () => {
const reactApp = uniq('reactapp');
runCLI(
`generate @nx/react:app ${reactApp} --rootProject=true --bundler=webpack --unitTestRunner=jest --e2eTestRunner=cypress --no-interactive`
);
runCLI('generate @nx/workspace:convert-to-monorepo --no-interactive');
checkFilesExist(
`apps/${reactApp}/src/main.tsx`,
`apps/e2e/cypress.config.ts`
);
expect(() => runCLI(`build ${reactApp}`)).not.toThrow();
expect(() => runCLI(`test ${reactApp}`)).not.toThrow();
expect(() => runCLI(`lint ${reactApp}`)).not.toThrow();
expect(() => runCLI(`lint e2e`)).not.toThrow();
expect(() => runCLI(`e2e e2e`)).not.toThrow();
});
});
describe('Workspace Tests', () => {
beforeAll(() => {
proj = newProject();
});
afterAll(() => cleanupProject());
describe('@nx/workspace:npm-package', () => {
it('should create a minimal npm package', () => {
const npmPackage = uniq('npm-package');
runCLI(`generate @nx/workspace:npm-package ${npmPackage}`);
updateFile('package.json', (content) => {
const json = JSON.parse(content);
json.workspaces = ['libs/*'];
return JSON.stringify(json);
});
const pmc = getPackageManagerCommand({
packageManager: getSelectedPackageManager(),
});
runCommand(pmc.install);
const result = runCLI(`test ${npmPackage}`);
expect(result).toContain('Hello World');
});
});
describe('move project', () => {
/**
* Tries moving a library from ${lib}/data-access -> shared/${lib}/data-access
*/
it('should work for libraries', async () => {
const lib1 = uniq('mylib');
const lib2 = uniq('mylib');
const lib3 = uniq('mylib');
runCLI(
`generate @nx/js:lib ${lib1}-data-access --directory=${lib1}/data-access --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
updateFile(
`${lib1}/data-access/src/lib/${lib1}-data-access.ts`,
`export function fromLibOne() { console.log('This is completely pointless'); }`
);
updateFile(
`${lib1}/data-access/src/index.ts`,
`export * from './lib/${lib1}-data-access.ts'`
);
/**
* Create a library which imports a class from lib1
*/
runCLI(
`generate @nx/js:lib ${lib2}-ui --directory=${lib2}/ui --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
updateFile(
`${lib2}/ui/src/lib/${lib2}-ui.ts`,
`import { fromLibOne } from '@${proj}/${lib1}-data-access';
export const fromLibTwo = () => fromLibOne();`
);
/**
* Create a library which has an implicit dependency on lib1
*/
runCLI(
`generate @nx/js:lib ${lib3} --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
updateFile(join(lib3, 'project.json'), (content) => {
const data = JSON.parse(content);
data.implicitDependencies = [`${lib1}-data-access`];
return JSON.stringify(data, null, 2);
});
/**
* Now try to move lib1
*/
const moveOutput = runCLI(
`generate @nx/workspace:move --project ${lib1}-data-access shared/${lib1}/data-access --newProjectName=shared-${lib1}-data-access --project-name-and-root-format=as-provided`
);
expect(moveOutput).toContain(`DELETE ${lib1}/data-access`);
expect(exists(`${lib1}/data-access`)).toBeFalsy();
const newPath = `shared/${lib1}/data-access`;
const newName = `shared-${lib1}-data-access`;
const readmePath = `${newPath}/README.md`;
expect(moveOutput).toContain(`CREATE ${readmePath}`);
checkFilesExist(readmePath);
const jestConfigPath = `${newPath}/jest.config.ts`;
expect(moveOutput).toContain(`CREATE ${jestConfigPath}`);
checkFilesExist(jestConfigPath);
const jestConfig = readFile(jestConfigPath);
expect(jestConfig).toContain(`displayName: 'shared-${lib1}-data-access'`);
expect(jestConfig).toContain(`preset: '../../../jest.preset.js'`);
expect(jestConfig).toContain(`'../../../coverage/${newPath}'`);
const tsConfigPath = `${newPath}/tsconfig.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigPath}`);
checkFilesExist(tsConfigPath);
const tsConfigLibPath = `${newPath}/tsconfig.lib.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigLibPath}`);
checkFilesExist(tsConfigLibPath);
const tsConfigLib = readJson(tsConfigLibPath);
expect(tsConfigLib.compilerOptions.outDir).toEqual(
'../../../dist/out-tsc'
);
const tsConfigSpecPath = `${newPath}/tsconfig.spec.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigSpecPath}`);
checkFilesExist(tsConfigSpecPath);
const tsConfigSpec = readJson(tsConfigSpecPath);
expect(tsConfigSpec.compilerOptions.outDir).toEqual(
'../../../dist/out-tsc'
);
const indexPath = `${newPath}/src/index.ts`;
expect(moveOutput).toContain(`CREATE ${indexPath}`);
checkFilesExist(indexPath);
const rootClassPath = `${newPath}/src/lib/${lib1}-data-access.ts`;
expect(moveOutput).toContain(`CREATE ${rootClassPath}`);
checkFilesExist(rootClassPath);
let projects = runCLI('show projects').split('\n');
expect(projects).not.toContain(`${lib1}-data-access`);
const newConfig = readJson(join(newPath, 'project.json'));
expect(newConfig).toMatchObject({
tags: [],
});
const lib3Config = readJson(join(lib3, 'project.json'));
expect(lib3Config.implicitDependencies).toEqual([
`shared-${lib1}-data-access`,
]);
expect(moveOutput).toContain('UPDATE tsconfig.base.json');
const rootTsConfig = readJson('tsconfig.base.json');
expect(
rootTsConfig.compilerOptions.paths[`@${proj}/${lib1}-data-access`]
).toBeUndefined();
expect(
rootTsConfig.compilerOptions.paths[
`@${proj}/shared-${lib1}-data-access`
]
).toEqual([`shared/${lib1}/data-access/src/index.ts`]);
projects = runCLI('show projects').split('\n');
expect(projects).not.toContain(`${lib1}-data-access`);
const project = readJson(join(newPath, 'project.json'));
expect(project).toBeTruthy();
expect(project.sourceRoot).toBe(`${newPath}/src`);
expect(project.targets.lint.options.lintFilePatterns).toEqual([
`shared/${lib1}/data-access/**/*.ts`,
`shared/${lib1}/data-access/package.json`,
]);
/**
* Check that the import in lib2 has been updated
*/
const lib2FilePath = `${lib2}/ui/src/lib/${lib2}-ui.ts`;
const lib2File = readFile(lib2FilePath);
expect(lib2File).toContain(
`import { fromLibOne } from '@${proj}/shared-${lib1}-data-access';`
);
});
it('should work for libs created with --importPath', async () => {
const importPath = '@wibble/fish';
const lib1 = uniq('mylib');
const lib2 = uniq('mylib');
const lib3 = uniq('mylib');
runCLI(
`generate @nx/js:lib ${lib1}-data-access --directory=${lib1}/data-access --importPath=${importPath} --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
updateFile(
`${lib1}/data-access/src/lib/${lib1}-data-access.ts`,
`export function fromLibOne() { console.log('This is completely pointless'); }`
);
updateFile(
`${lib1}/data-access/src/index.ts`,
`export * from './lib/${lib1}-data-access.ts'`
);
/**
* Create a library which imports a class from lib1
*/
runCLI(
`generate @nx/js:lib ${lib2}-ui --directory=${lib2}/ui --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
updateFile(
`${lib2}/ui/src/lib/${lib2}-ui.ts`,
`import { fromLibOne } from '${importPath}';
export const fromLibTwo = () => fromLibOne();`
);
/**
* Create a library which has an implicit dependency on lib1
*/
runCLI(
`generate @nx/js:lib ${lib3} --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
updateFile(join(lib3, 'project.json'), (content) => {
const data = JSON.parse(content);
data.implicitDependencies = [`${lib1}-data-access`];
return JSON.stringify(data, null, 2);
});
/**
* Now try to move lib1
*/
const moveOutput = runCLI(
`generate @nx/workspace:move --project ${lib1}-data-access shared/${lib1}/data-access --newProjectName=shared-${lib1}-data-access --project-name-and-root-format=as-provided`
);
expect(moveOutput).toContain(`DELETE ${lib1}/data-access`);
expect(exists(`${lib1}/data-access`)).toBeFalsy();
const newPath = `shared/${lib1}/data-access`;
const newName = `shared-${lib1}-data-access`;
const readmePath = `${newPath}/README.md`;
expect(moveOutput).toContain(`CREATE ${readmePath}`);
checkFilesExist(readmePath);
const jestConfigPath = `${newPath}/jest.config.ts`;
expect(moveOutput).toContain(`CREATE ${jestConfigPath}`);
checkFilesExist(jestConfigPath);
const jestConfig = readFile(jestConfigPath);
expect(jestConfig).toContain(`displayName: 'shared-${lib1}-data-access'`);
expect(jestConfig).toContain(`preset: '../../../jest.preset.js'`);
expect(jestConfig).toContain(`'../../../coverage/${newPath}'`);
const tsConfigPath = `${newPath}/tsconfig.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigPath}`);
checkFilesExist(tsConfigPath);
const tsConfigLibPath = `${newPath}/tsconfig.lib.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigLibPath}`);
checkFilesExist(tsConfigLibPath);
const tsConfigLib = readJson(tsConfigLibPath);
expect(tsConfigLib.compilerOptions.outDir).toEqual(
'../../../dist/out-tsc'
);
const tsConfigSpecPath = `${newPath}/tsconfig.spec.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigSpecPath}`);
checkFilesExist(tsConfigSpecPath);
const tsConfigSpec = readJson(tsConfigSpecPath);
expect(tsConfigSpec.compilerOptions.outDir).toEqual(
'../../../dist/out-tsc'
);
const indexPath = `${newPath}/src/index.ts`;
expect(moveOutput).toContain(`CREATE ${indexPath}`);
checkFilesExist(indexPath);
const rootClassPath = `${newPath}/src/lib/${lib1}-data-access.ts`;
expect(moveOutput).toContain(`CREATE ${rootClassPath}`);
checkFilesExist(rootClassPath);
expect(moveOutput).toContain('UPDATE tsconfig.base.json');
const rootTsConfig = readJson('tsconfig.base.json');
expect(
rootTsConfig.compilerOptions.paths[`@${proj}/${lib1}-data-access`]
).toBeUndefined();
expect(
rootTsConfig.compilerOptions.paths[
`@${proj}/shared-${lib1}-data-access`
]
).toEqual([`shared/${lib1}/data-access/src/index.ts`]);
const projects = runCLI('show projects').split('\n');
expect(projects).not.toContain(`${lib1}-data-access`);
const project = readJson(join(newPath, 'project.json'));
expect(project).toBeTruthy();
expect(project.sourceRoot).toBe(`${newPath}/src`);
expect(project.tags).toEqual([]);
const lib3Config = readJson(join(lib3, 'project.json'));
expect(lib3Config.implicitDependencies).toEqual([newName]);
expect(project.targets.lint.options.lintFilePatterns).toEqual([
`shared/${lib1}/data-access/**/*.ts`,
`shared/${lib1}/data-access/package.json`,
]);
/**
* Check that the import in lib2 has been updated
*/
const lib2FilePath = `${lib2}/ui/src/lib/${lib2}-ui.ts`;
const lib2File = readFile(lib2FilePath);
expect(lib2File).toContain(
`import { fromLibOne } from '@${proj}/shared-${lib1}-data-access';`
);
});
it('should work for custom workspace layouts with --project-name-and-root-format=derived', async () => {
const lib1 = uniq('mylib');
const lib2 = uniq('mylib');
const lib3 = uniq('mylib');
let nxJson = readJson('nx.json');
nxJson.workspaceLayout = { libsDir: 'packages' };
updateFile('nx.json', JSON.stringify(nxJson));
runCLI(
`generate @nx/js:lib ${lib1}/data-access --unitTestRunner=jest --project-name-and-root-format=derived`
);
updateFile(
`packages/${lib1}/data-access/src/lib/${lib1}-data-access.ts`,
`export function fromLibOne() { console.log('This is completely pointless'); }`
);
updateFile(
`packages/${lib1}/data-access/src/index.ts`,
`export * from './lib/${lib1}-data-access.ts'`
);
/**
* Create a library which imports a class from lib1
*/
runCLI(
`generate @nx/js:lib ${lib2}/ui --unitTestRunner=jest --project-name-and-root-format=derived`
);
updateFile(
`packages/${lib2}/ui/src/lib/${lib2}-ui.ts`,
`import { fromLibOne } from '@${proj}/${lib1}/data-access';
export const fromLibTwo = () => fromLibOne();`
);
/**
* Create a library which has an implicit dependency on lib1
*/
runCLI(
`generate @nx/js:lib ${lib3} --unitTestRunner=jest --project-name-and-root-format=derived`
);
updateFile(join('packages', lib3, 'project.json'), (content) => {
const data = JSON.parse(content);
data.implicitDependencies = [`${lib1}-data-access`];
return JSON.stringify(data, null, 2);
});
/**
* Now try to move lib1
*/
const moveOutput = runCLI(
`generate @nx/workspace:move --project ${lib1}-data-access shared/${lib1}/data-access --project-name-and-root-format=derived`
);
expect(moveOutput).toContain(`DELETE packages/${lib1}/data-access`);
expect(exists(`packages/${lib1}/data-access`)).toBeFalsy();
const newPath = `packages/shared/${lib1}/data-access`;
const newName = `shared-${lib1}-data-access`;
const readmePath = `${newPath}/README.md`;
expect(moveOutput).toContain(`CREATE ${readmePath}`);
checkFilesExist(readmePath);
const jestConfigPath = `${newPath}/jest.config.ts`;
expect(moveOutput).toContain(`CREATE ${jestConfigPath}`);
checkFilesExist(jestConfigPath);
const jestConfig = readFile(jestConfigPath);
expect(jestConfig).toContain(`displayName: 'shared-${lib1}-data-access'`);
expect(jestConfig).toContain(`preset: '../../../../jest.preset.js'`);
expect(jestConfig).toContain(`'../../../../coverage/${newPath}'`);
const tsConfigPath = `${newPath}/tsconfig.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigPath}`);
checkFilesExist(tsConfigPath);
const tsConfigLibPath = `${newPath}/tsconfig.lib.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigLibPath}`);
checkFilesExist(tsConfigLibPath);
const tsConfigLib = readJson(tsConfigLibPath);
expect(tsConfigLib.compilerOptions.outDir).toEqual(
'../../../../dist/out-tsc'
);
const tsConfigSpecPath = `${newPath}/tsconfig.spec.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigSpecPath}`);
checkFilesExist(tsConfigSpecPath);
const tsConfigSpec = readJson(tsConfigSpecPath);
expect(tsConfigSpec.compilerOptions.outDir).toEqual(
'../../../../dist/out-tsc'
);
const indexPath = `${newPath}/src/index.ts`;
expect(moveOutput).toContain(`CREATE ${indexPath}`);
checkFilesExist(indexPath);
const rootClassPath = `${newPath}/src/lib/${lib1}-data-access.ts`;
expect(moveOutput).toContain(`CREATE ${rootClassPath}`);
checkFilesExist(rootClassPath);
expect(moveOutput).toContain('UPDATE tsconfig.base.json');
const rootTsConfig = readJson('tsconfig.base.json');
expect(
rootTsConfig.compilerOptions.paths[`@${proj}/${lib1}/data-access`]
).toBeUndefined();
expect(
rootTsConfig.compilerOptions.paths[
`@${proj}/shared/${lib1}/data-access`
]
).toEqual([`packages/shared/${lib1}/data-access/src/index.ts`]);
const projects = runCLI('show projects').split('\n');
expect(projects).not.toContain(`${lib1}-data-access`);
const project = readJson(join(newPath, 'project.json'));
expect(project).toBeTruthy();
expect(project.sourceRoot).toBe(`${newPath}/src`);
expect(project.targets.lint.options.lintFilePatterns).toEqual([
`packages/shared/${lib1}/data-access/**/*.ts`,
`packages/shared/${lib1}/data-access/package.json`,
]);
expect(project.tags).toEqual([]);
/**
* Check that the import in lib2 has been updated
*/
const lib2FilePath = `packages/${lib2}/ui/src/lib/${lib2}-ui.ts`;
const lib2File = readFile(lib2FilePath);
expect(lib2File).toContain(
`import { fromLibOne } from '@${proj}/shared/${lib1}/data-access';`
);
nxJson = readJson('nx.json');
delete nxJson.workspaceLayout;
updateFile('nx.json', JSON.stringify(nxJson));
});
it('should work when moving a lib to a subfolder', async () => {
const lib1 = uniq('lib1');
const lib2 = uniq('lib2');
const lib3 = uniq('lib3');
runCLI(
`generate @nx/js:lib ${lib1} --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
updateFile(
`${lib1}/src/lib/${lib1}.ts`,
`export function fromLibOne() { console.log('This is completely pointless'); }`
);
updateFile(`${lib1}/src/index.ts`, `export * from './lib/${lib1}.ts'`);
/**
* Create a library which imports a class from lib1
*/
runCLI(
`generate @nx/js:lib ${lib2}-ui --directory=${lib2}/ui --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
updateFile(
`${lib2}/ui/src/lib/${lib2}-ui.ts`,
`import { fromLibOne } from '@${proj}/${lib1}';
export const fromLibTwo = () => fromLibOne();`
);
/**
* Create a library which has an implicit dependency on lib1
*/
runCLI(
`generate @nx/js:lib ${lib3} --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
updateFile(join(lib3, 'project.json'), (content) => {
const data = JSON.parse(content);
data.implicitDependencies = [lib1];
return JSON.stringify(data, null, 2);
});
/**
* Now try to move lib1
*/
const moveOutput = runCLI(
`generate @nx/workspace:move --project ${lib1} ${lib1}/data-access --newProjectName=${lib1}-data-access --project-name-and-root-format=as-provided`
);
expect(moveOutput).toContain(`DELETE ${lib1}/project.json`);
expect(exists(`${lib1}/project.json`)).toBeFalsy();
const newPath = `${lib1}/data-access`;
const newName = `${lib1}-data-access`;
const readmePath = `${newPath}/README.md`;
expect(moveOutput).toContain(`CREATE ${readmePath}`);
checkFilesExist(readmePath);
const jestConfigPath = `${newPath}/jest.config.ts`;
expect(moveOutput).toContain(`CREATE ${jestConfigPath}`);
checkFilesExist(jestConfigPath);
const jestConfig = readFile(jestConfigPath);
expect(jestConfig).toContain(`displayName: '${lib1}-data-access'`);
expect(jestConfig).toContain(`preset: '../../jest.preset.js'`);
expect(jestConfig).toContain(`'../../coverage/${newPath}'`);
const tsConfigPath = `${newPath}/tsconfig.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigPath}`);
checkFilesExist(tsConfigPath);
const tsConfigLibPath = `${newPath}/tsconfig.lib.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigLibPath}`);
checkFilesExist(tsConfigLibPath);
const tsConfigLib = readJson(tsConfigLibPath);
expect(tsConfigLib.compilerOptions.outDir).toEqual('../../dist/out-tsc');
const tsConfigSpecPath = `${newPath}/tsconfig.spec.json`;
expect(moveOutput).toContain(`CREATE ${tsConfigSpecPath}`);
checkFilesExist(tsConfigSpecPath);
const tsConfigSpec = readJson(tsConfigSpecPath);
expect(tsConfigSpec.compilerOptions.outDir).toEqual('../../dist/out-tsc');
const indexPath = `${newPath}/src/index.ts`;
expect(moveOutput).toContain(`CREATE ${indexPath}`);
checkFilesExist(indexPath);
const rootClassPath = `${newPath}/src/lib/${lib1}.ts`;
expect(moveOutput).toContain(`CREATE ${rootClassPath}`);
checkFilesExist(rootClassPath);
let projects = runCLI('show projects').split('\n');
expect(projects).not.toContain(lib1);
const newConfig = readJson(join(newPath, 'project.json'));
expect(newConfig).toMatchObject({
tags: [],
});
const lib3Config = readJson(join(lib3, 'project.json'));
expect(lib3Config.implicitDependencies).toEqual([`${lib1}-data-access`]);
expect(moveOutput).toContain('UPDATE tsconfig.base.json');
const rootTsConfig = readJson('tsconfig.base.json');
expect(
rootTsConfig.compilerOptions.paths[`@${proj}/${lib1}`]
).toBeUndefined();
expect(
rootTsConfig.compilerOptions.paths[`@${proj}/${lib1}-data-access`]
).toEqual([`${lib1}/data-access/src/index.ts`]);
projects = runCLI('show projects').split('\n');
expect(projects).not.toContain(lib1);
const project = readJson(join(newPath, 'project.json'));
expect(project).toBeTruthy();
expect(project.sourceRoot).toBe(`${newPath}/src`);
expect(project.targets.lint.options.lintFilePatterns).toEqual([
`${lib1}/data-access/**/*.ts`,
`${lib1}/data-access/package.json`,
]);
/**
* Check that the import in lib2 has been updated
*/
const lib2FilePath = `${lib2}/ui/src/lib/${lib2}-ui.ts`;
const lib2File = readFile(lib2FilePath);
expect(lib2File).toContain(
`import { fromLibOne } from '@${proj}/${lib1}-data-access';`
);
});
it('should work for libraries when scope is unset', async () => {
const json = readJson('package.json');
json.name = proj;
updateFile('package.json', JSON.stringify(json));
const lib1 = uniq('mylib');
const lib2 = uniq('mylib');
const lib3 = uniq('mylib');
runCLI(
`generate @nx/js:lib ${lib1}-data-access --directory=${lib1}/data-access --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
let rootTsConfig = readJson('tsconfig.base.json');
expect(
rootTsConfig.compilerOptions.paths[`@${proj}/${lib1}-data-access`]
).toBeUndefined();
expect(
rootTsConfig.compilerOptions.paths[`${lib1}-data-access`]
).toBeDefined();
updateFile(
`${lib1}/data-access/src/lib/${lib1}-data-access.ts`,
`export function fromLibOne() { console.log('This is completely pointless'); }`
);
updateFile(
`${lib1}/data-access/src/index.ts`,
`export * from './lib/${lib1}-data-access.ts'`
);
/**
* Create a library which imports a class from lib1
*/
runCLI(
`generate @nx/js:lib ${lib2}-ui --directory=${lib2}/ui --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
updateFile(
`${lib2}/ui/src/lib/${lib2}-ui.ts`,
`import { fromLibOne } from '${lib1}-data-access';
export const fromLibTwo = () => fromLibOne();`
);
/**
* Create a library which has an implicit dependency on lib1
*/
runCLI(
`generate @nx/js:lib ${lib3} --unitTestRunner=jest --project-name-and-root-format=as-provided`
);
updateFile(join(lib3, 'project.json'), (content) => {
const data = JSON.parse(content);
data.implicitDependencies = [`${lib1}-data-access`];
return JSON.stringify(data, null, 2);
});
/**
* Now try to move lib1
*/
const moveOutput = runCLI(
`generate @nx/workspace:move --project ${lib1}-data-access shared/${lib1}/data-access --newProjectName=shared-${lib1}-data-access --project-name-and-root-format=as-provided`
);
expect(moveOutput).toContain(`DELETE ${lib1}/data-access`);
expect(exists(`${lib1}/data-access`)).toBeFalsy();
const newPath = `shared/${lib1}/data-access`;
const newName = `shared-${lib1}-data-access`;
const readmePath = `${newPath}/README.md`;
expect(moveOutput).toContain(`CREATE ${readmePath}`);
checkFilesExist(readmePath);
const indexPath = `${newPath}/src/index.ts`;
expect(moveOutput).toContain(`CREATE ${indexPath}`);
checkFilesExist(indexPath);
const rootClassPath = `${newPath}/src/lib/${lib1}-data-access.ts`;
expect(moveOutput).toContain(`CREATE ${rootClassPath}`);
checkFilesExist(rootClassPath);
const newConfig = readJson(join(newPath, 'project.json'));
expect(newConfig).toMatchObject({
tags: [],
});
const lib3Config = readJson(join(lib3, 'project.json'));
expect(lib3Config.implicitDependencies).toEqual([
`shared-${lib1}-data-access`,
]);
expect(moveOutput).toContain('UPDATE tsconfig.base.json');
rootTsConfig = readJson('tsconfig.base.json');
expect(
rootTsConfig.compilerOptions.paths[`${lib1}-data-access`]
).toBeUndefined();
expect(
rootTsConfig.compilerOptions.paths[`shared-${lib1}-data-access`]
).toEqual([`shared/${lib1}/data-access/src/index.ts`]);
const projects = runCLI('show projects').split('\n');
expect(projects).not.toContain(`${lib1}-data-access`);
const project = readJson(join(newPath, 'project.json'));
expect(project).toBeTruthy();
expect(project.sourceRoot).toBe(`${newPath}/src`);
expect(project.targets.lint.options.lintFilePatterns).toEqual([
`shared/${lib1}/data-access/**/*.ts`,
`shared/${lib1}/data-access/package.json`,
]);
/**
* Check that the import in lib2 has been updated
*/
const lib2FilePath = `${lib2}/ui/src/lib/${lib2}-ui.ts`;
const lib2File = readFile(lib2FilePath);
expect(lib2File).toContain(
`import { fromLibOne } from 'shared-${lib1}-data-access';`
);
});
});
describe('remove project', () => {
/**
* Tries creating then deleting a lib
*/
it('should work', async () => {
const lib1 = uniq('myliba');
const lib2 = uniq('mylibb');
runCLI(`generate @nx/js:lib ${lib1} --unitTestRunner=jest`);
expect(exists(tmpProjPath(`libs/${lib1}`))).toBeTruthy();
/**
* Create a library which has an implicit dependency on lib1
*/
runCLI(`generate @nx/js:lib ${lib2} --unitTestRunner=jest`);
updateFile(join('libs', lib2, 'project.json'), (content) => {
const data = JSON.parse(content);
data.implicitDependencies = [lib1];
return JSON.stringify(data, null, 2);
});
/**
* Try removing the project (should fail)
*/
let error;
try {
console.log(runCLI(`generate @nx/workspace:remove --project ${lib1}`));
} catch (e) {
error = e;
}
expect(error).toBeDefined();
expect(error.stdout.toString()).toContain(
`${lib1} is still a dependency of the following projects`
);
expect(error.stdout.toString()).toContain(lib2);
/**
* Try force removing the project
*/
const removeOutputForced = runCLI(
`generate @nx/workspace:remove --project ${lib1} --forceRemove`
);
expect(removeOutputForced).toContain(`DELETE libs/${lib1}`);
expect(exists(tmpProjPath(`libs/${lib1}`))).toBeFalsy();
expect(removeOutputForced).not.toContain(`UPDATE nx.json`);
const projects = runCLI('show projects').split('\n');
expect(projects).not.toContain(lib1);
const lib2Config = readJson(join('libs', lib2, 'project.json'));
expect(lib2Config.implicitDependencies).toEqual([]);
expect(projects[`${lib1}`]).toBeUndefined();
});
});
});
|
1,999 | 0 | petrpan-code/nrwl/nx/e2e/nx-run | petrpan-code/nrwl/nx/e2e/nx-run/src/affected-graph.test.ts | import type { NxJsonConfiguration } from '@nx/devkit';
import {
getPackageManagerCommand,
isNotWindows,
newProject,
readFile,
readJson,
cleanupProject,
runCLI,
runCLIAsync,
runCommand,
uniq,
updateFile,
checkFilesExist,
isWindows,
fileExists,
removeFile,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('Nx Affected and Graph Tests', () => {
let proj: string;
beforeAll(() => (proj = newProject()));
afterAll(() => cleanupProject());
describe('affected:*', () => {
it('should print, build, and test affected apps', async () => {
process.env.CI = 'true';
const myapp = uniq('myapp');
const myapp2 = uniq('myapp2');
const mylib = uniq('mylib');
const mylib2 = uniq('mylib2');
const mypublishablelib = uniq('mypublishablelib');
runCLI(`generate @nx/web:app ${myapp}`);
runCLI(`generate @nx/web:app ${myapp2}`);
runCLI(`generate @nx/js:lib ${mylib}`);
runCLI(`generate @nx/js:lib ${mylib2}`);
runCLI(
`generate @nx/js:lib ${mypublishablelib} --publishable --importPath=@${proj}/${mypublishablelib} --tags=ui`
);
updateFile(
`apps/${myapp}/src/app/app.element.spec.ts`,
`
import * as x from '@${proj}/${mylib}';
describe('sample test', () => {
it('should test', () => {
expect(1).toEqual(1);
});
});
`
);
updateFile(
`libs/${mypublishablelib}/src/lib/${mypublishablelib}.spec.ts`,
`
import * as x from '@${proj}/${mylib}';
describe('sample test', () => {
it('should test', () => {
expect(1).toEqual(1);
});
});
`
);
const affectedProjects = runCLI(
`show projects --affected --files="libs/${mylib}/src/index.ts"`
);
expect(affectedProjects).toContain(myapp);
expect(affectedProjects).not.toContain(myapp2);
let affectedLibs = runCLI(
`show projects --affected --files="libs/${mylib}/src/index.ts" --type lib`
);
// type lib shows no apps
expect(affectedLibs).not.toContain(myapp);
expect(affectedLibs).not.toContain(myapp2);
expect(affectedLibs).toContain(mylib);
const implicitlyAffectedApps = runCLI(
'show projects --affected --files="tsconfig.base.json"'
);
expect(implicitlyAffectedApps).toContain(myapp);
expect(implicitlyAffectedApps).toContain(myapp2);
const noAffectedApps = runCLI(
'show projects --affected projects --files="README.md"'
);
expect(noAffectedApps).not.toContain(myapp);
expect(noAffectedApps).not.toContain(myapp2);
affectedLibs = runCLI(
`show projects --affected --files="libs/${mylib}/src/index.ts"`
);
expect(affectedLibs).toContain(mypublishablelib);
expect(affectedLibs).toContain(mylib);
expect(affectedLibs).not.toContain(mylib2);
const implicitlyAffectedLibs = runCLI(
'show projects --affected --files="tsconfig.base.json"'
);
expect(implicitlyAffectedLibs).toContain(mypublishablelib);
expect(implicitlyAffectedLibs).toContain(mylib);
expect(implicitlyAffectedLibs).toContain(mylib2);
const noAffectedLibsNonExistentFile = runCLI(
'show projects --affected --files="tsconfig.json"'
);
expect(noAffectedLibsNonExistentFile).not.toContain(mypublishablelib);
expect(noAffectedLibsNonExistentFile).not.toContain(mylib);
expect(noAffectedLibsNonExistentFile).not.toContain(mylib2);
const noAffectedLibs = runCLI(
'show projects --affected --files="README.md"'
);
expect(noAffectedLibs).not.toContain(mypublishablelib);
expect(noAffectedLibs).not.toContain(mylib);
expect(noAffectedLibs).not.toContain(mylib2);
// build
const build = runCLI(
`affected:build --files="libs/${mylib}/src/index.ts" --parallel`
);
expect(build).toContain(`Running target build for 3 projects:`);
expect(build).toContain(`- ${myapp}`);
expect(build).toContain(`- ${mypublishablelib}`);
expect(build).not.toContain('is not registered with the build command');
expect(build).toContain('Successfully ran target build');
const buildExcluded = runCLI(
`affected:build --files="libs/${mylib}/src/index.ts" --exclude=${myapp}`
);
expect(buildExcluded).toContain(`Running target build for 2 projects:`);
expect(buildExcluded).toContain(`- ${mypublishablelib}`);
const buildExcludedByTag = runCLI(
`affected:build --files="libs/${mylib}/src/index.ts" --exclude=tag:ui`
);
expect(buildExcludedByTag).toContain(
`Running target build for 2 projects:`
);
expect(buildExcludedByTag).not.toContain(`- ${mypublishablelib}`);
// test
updateFile(
`apps/${myapp}/src/app/app.element.spec.ts`,
readFile(`apps/${myapp}/src/app/app.element.spec.ts`).replace(
'.toEqual(1)',
'.toEqual(2)'
)
);
const failedTests = runCLI(
`affected:test --files="libs/${mylib}/src/index.ts"`,
{ silenceError: true }
);
expect(failedTests).toContain(mylib);
expect(failedTests).toContain(myapp);
expect(failedTests).toContain(mypublishablelib);
expect(failedTests).toContain(`Failed tasks:`);
// Fix failing Unit Test
updateFile(
`apps/${myapp}/src/app/app.element.spec.ts`,
readFile(`apps/${myapp}/src/app/app.element.spec.ts`).replace(
'.toEqual(2)',
'.toEqual(1)'
)
);
}, 1000000);
});
describe('affected (with git)', () => {
let myapp;
let myapp2;
let mylib;
beforeEach(() => {
myapp = uniq('myapp');
myapp2 = uniq('myapp');
mylib = uniq('mylib');
const nxJson: NxJsonConfiguration = readJson('nx.json');
updateFile('nx.json', JSON.stringify(nxJson));
runCommand(`git init`);
runCommand(`git config user.email "[email protected]"`);
runCommand(`git config user.name "Test"`);
runCommand(`git config commit.gpgsign false`);
try {
runCommand(
`git add . && git commit -am "initial commit" && git checkout -b main`
);
} catch (e) {}
});
function generateAll() {
runCLI(`generate @nx/web:app ${myapp}`);
runCLI(`generate @nx/web:app ${myapp2}`);
runCLI(`generate @nx/js:lib ${mylib}`);
runCommand(`git add . && git commit -am "add all"`);
}
it('should not affect other projects by generating a new project', () => {
// TODO: investigate why affected gives different results on windows
if (isNotWindows()) {
runCLI(`generate @nx/web:app ${myapp}`);
expect(runCLI('print-affected --select projects')).toContain(myapp);
runCommand(`git add . && git commit -am "add ${myapp}"`);
runCLI(`generate @nx/web:app ${myapp2}`);
let output = runCLI('print-affected --select projects');
expect(output).not.toContain(myapp);
expect(output).toContain(myapp2);
runCommand(`git add . && git commit -am "add ${myapp2}"`);
runCLI(`generate @nx/js:lib ${mylib}`);
output = runCLI('print-affected --select projects');
expect(output).not.toContain(myapp);
expect(output).not.toContain(myapp2);
expect(output).toContain(mylib);
}
}, 1000000);
it('should detect changes to projects based on tags changes', async () => {
// TODO: investigate why affected gives different results on windows
if (isNotWindows()) {
generateAll();
updateFile(join('apps', myapp, 'project.json'), (content) => {
const data = JSON.parse(content);
data.tags = ['tag'];
return JSON.stringify(data, null, 2);
});
const output = runCLI('print-affected --select projects');
expect(output).toContain(myapp);
expect(output).not.toContain(myapp2);
expect(output).not.toContain(mylib);
}
});
it('should affect all projects by removing projects', async () => {
generateAll();
const root = `libs/${mylib}`;
removeFile(root);
const output = runCLI('print-affected --select projects');
expect(output).toContain(myapp);
expect(output).toContain(myapp2);
expect(output).not.toContain(mylib);
});
it('should detect changes to implicitly dependant projects', async () => {
generateAll();
updateFile(join('apps', myapp, 'project.json'), (content) => {
const data = JSON.parse(content);
data.implicitDependencies = ['*', `!${myapp2}`];
return JSON.stringify(data, null, 2);
});
runCommand('git commit -m "setup test"');
updateFile(`libs/${mylib}/index.html`, '<html></html>');
const output = runCLI('print-affected --select projects');
expect(output).toContain(myapp);
expect(output).not.toContain(myapp2);
expect(output).toContain(mylib);
// Clear implicit deps to not interfere with other tests.
updateFile(join('apps', myapp, 'project.json'), (content) => {
const data = JSON.parse(content);
data.implicitDependencies = [];
return JSON.stringify(data, null, 2);
});
});
it('should handle file renames', () => {
generateAll();
// Move file
updateFile(
`apps/${myapp2}/src/index.html`,
readFile(`apps/${myapp}/src/index.html`)
);
removeFile(`apps/${myapp}/src/index.html`);
const affectedProjects = runCLI(
'print-affected --uncommitted --select projects'
)
.replace(
/.*nx print-affected --uncommitted --select projects( --verbose)?\n/,
''
)
.split(', ');
expect(affectedProjects).toContain(myapp);
expect(affectedProjects).toContain(myapp2);
});
});
describe('graph', () => {
let myapp: string;
let myapp2: string;
let myapp3: string;
let myappE2e: string;
let myapp2E2e: string;
let myapp3E2e: string;
let mylib: string;
let mylib2: string;
beforeAll(() => {
myapp = uniq('myapp');
myapp2 = uniq('myapp2');
myapp3 = uniq('myapp3');
myappE2e = `${myapp}-e2e`;
myapp2E2e = `${myapp2}-e2e`;
myapp3E2e = `${myapp3}-e2e`;
mylib = uniq('mylib');
mylib2 = uniq('mylib2');
runCLI(`generate @nx/web:app ${myapp}`);
runCLI(`generate @nx/web:app ${myapp2}`);
runCLI(`generate @nx/web:app ${myapp3}`);
runCLI(`generate @nx/js:lib ${mylib}`);
runCLI(`generate @nx/js:lib ${mylib2}`);
runCommand(`git init`);
runCommand(`git config user.email "[email protected]"`);
runCommand(`git config user.name "Test"`);
runCommand(`git config commit.gpgsign false`);
runCommand(
`git add . && git commit -am "initial commit" && git checkout -b main`
);
updateFile(
`apps/${myapp}/src/main.ts`,
`
import '@${proj}/${mylib}';
const s = {loadChildren: '@${proj}/${mylib2}'};
`
);
updateFile(
`apps/${myapp2}/src/app/app.element.spec.ts`,
`import '@${proj}/${mylib}';`
);
updateFile(
`libs/${mylib}/src/${mylib}.spec.ts`,
`import '@${proj}/${mylib2}';`
);
});
it('graph should output json to file', () => {
runCLI(`graph --file=project-graph.json`);
expect(() => checkFilesExist('project-graph.json')).not.toThrow();
const jsonFileContents = readJson('project-graph.json');
expect(jsonFileContents.graph.dependencies).toEqual(
expect.objectContaining({
[myapp3E2e]: [
{
source: myapp3E2e,
target: myapp3,
type: 'implicit',
},
],
[myapp2]: [
{
source: myapp2,
target: mylib,
type: 'static',
},
],
[myapp2E2e]: [
{
source: myapp2E2e,
target: myapp2,
type: 'implicit',
},
],
[mylib]: [
{
source: mylib,
target: mylib2,
type: 'static',
},
],
[mylib2]: [],
[myapp]: [
{
source: myapp,
target: mylib,
type: 'static',
},
],
[myappE2e]: [
{
source: myappE2e,
target: myapp,
type: 'implicit',
},
],
[myapp3]: [],
})
);
runCLI(
`affected:graph --files="libs/${mylib}/src/index.ts" --file="project-graph.json"`
);
expect(() => checkFilesExist('project-graph.json')).not.toThrow();
const jsonFileContents2 = readJson('project-graph.json');
expect(jsonFileContents2.criticalPath).toContain(myapp);
expect(jsonFileContents2.criticalPath).toContain(myapp2);
expect(jsonFileContents2.criticalPath).toContain(mylib);
expect(jsonFileContents2.criticalPath).not.toContain(mylib2);
}, 1000000);
if (isNotWindows()) {
it('graph should output json to file by absolute path', () => {
runCLI(`graph --file=/tmp/project-graph.json`);
expect(() => checkFilesExist('/tmp/project-graph.json')).not.toThrow();
}, 1000000);
}
if (isWindows()) {
it('graph should output json to file by absolute path in Windows', () => {
runCLI(`graph --file=C:\\tmp\\project-graph.json`);
expect(fileExists('C:\\tmp\\project-graph.json')).toBeTruthy();
}, 1000000);
}
it('graph should focus requested project', () => {
runCLI(`graph --focus=${myapp} --file=project-graph.json`);
expect(() => checkFilesExist('project-graph.json')).not.toThrow();
const jsonFileContents = readJson('project-graph.json');
const projectNames = Object.keys(jsonFileContents.graph.nodes);
expect(projectNames).toContain(myapp);
expect(projectNames).toContain(mylib);
expect(projectNames).toContain(mylib2);
expect(projectNames).toContain(myappE2e);
expect(projectNames).not.toContain(myapp2);
expect(projectNames).not.toContain(myapp3);
expect(projectNames).not.toContain(myapp2E2e);
expect(projectNames).not.toContain(myapp3E2e);
}, 1000000);
it('graph should exclude requested projects', () => {
runCLI(
`graph --exclude=${myappE2e},${myapp2E2e},${myapp3E2e} --file=project-graph.json`
);
expect(() => checkFilesExist('project-graph.json')).not.toThrow();
const jsonFileContents = readJson('project-graph.json');
const projectNames = Object.keys(jsonFileContents.graph.nodes);
expect(projectNames).toContain(myapp);
expect(projectNames).toContain(mylib);
expect(projectNames).toContain(mylib2);
expect(projectNames).toContain(myapp2);
expect(projectNames).toContain(myapp3);
expect(projectNames).not.toContain(myappE2e);
expect(projectNames).not.toContain(myapp2E2e);
expect(projectNames).not.toContain(myapp3E2e);
}, 1000000);
it('graph should exclude requested projects that were included by a focus', () => {
runCLI(
`graph --focus=${myapp} --exclude=${myappE2e} --file=project-graph.json`
);
expect(() => checkFilesExist('project-graph.json')).not.toThrow();
const jsonFileContents = readJson('project-graph.json');
const projectNames = Object.keys(jsonFileContents.graph.nodes);
expect(projectNames).toContain(myapp);
expect(projectNames).toContain(mylib);
expect(projectNames).toContain(mylib2);
expect(projectNames).not.toContain(myappE2e);
expect(projectNames).not.toContain(myapp2);
expect(projectNames).not.toContain(myapp3);
expect(projectNames).not.toContain(myapp2E2e);
expect(projectNames).not.toContain(myapp3E2e);
}, 1000000);
it('graph should output a deployable static website in an html file accompanied by a folder with static assets', () => {
runCLI(`graph --file=project-graph.html`);
expect(() => checkFilesExist('project-graph.html')).not.toThrow();
expect(() => checkFilesExist('static/styles.css')).not.toThrow();
expect(() => checkFilesExist('static/runtime.js')).not.toThrow();
expect(() => checkFilesExist('static/main.js')).not.toThrow();
expect(() => checkFilesExist('static/environment.js')).not.toThrow();
const environmentJs = readFile('static/environment.js');
expect(environmentJs).toContain('window.projectGraphResponse');
expect(environmentJs).toContain('"affected":[]');
});
it('graph should output valid json when stdout is specified', () => {
const result = runCLI(`affected -t build --graph stdout`);
let model;
expect(() => (model = JSON.parse(result))).not.toThrow();
expect(model).toHaveProperty('graph');
expect(model).toHaveProperty('tasks');
});
it('should include affected projects in environment file', () => {
runCLI(`graph --affected --file=project-graph.html`);
const environmentJs = readFile('static/environment.js');
const affectedProjects = environmentJs
.match(/"affected":\[(.*?)\]/)[1]
?.split(',');
expect(affectedProjects).toContain(`"${myapp}"`);
expect(affectedProjects).toContain(`"${myappE2e}"`);
expect(affectedProjects).toContain(`"${myapp2}"`);
expect(affectedProjects).toContain(`"${myapp2E2e}"`);
expect(affectedProjects).toContain(`"${mylib}"`);
});
});
});
describe('Print-affected', () => {
let proj: string;
beforeAll(() => (proj = newProject()));
afterAll(() => cleanupProject());
it('should print information about affected projects', async () => {
const myapp = uniq('myapp-a');
const myapp2 = uniq('myapp-b');
const mylib = uniq('mylib');
const mylib2 = uniq('mylib2');
const mypublishablelib = uniq('mypublishablelib');
runCLI(`generate @nx/web:app ${myapp}`);
runCLI(`generate @nx/web:app ${myapp2}`);
runCLI(`generate @nx/js:lib ${mylib}`);
runCLI(`generate @nx/js:lib ${mylib2}`);
runCLI(`generate @nx/js:lib ${mypublishablelib}`);
const app1ElementSpec = readFile(
`apps/${myapp}/src/app/app.element.spec.ts`
);
updateFile(
`apps/${myapp}/src/app/app.element.spec.ts`,
`
import "@${proj}/${mylib}";
import "@${proj}/${mypublishablelib}";
${app1ElementSpec}
`
);
const app2ElementSpec = readFile(
`apps/${myapp2}/src/app/app.element.spec.ts`
);
updateFile(
`apps/${myapp2}/src/app/app.element.spec.ts`,
`
import "@${proj}/${mylib}";
import "@${proj}/${mypublishablelib}";
${app2ElementSpec}
`
);
const resWithoutTarget = JSON.parse(
(
await runCLIAsync(
`print-affected --files=apps/${myapp}/src/app/app.element.spec.ts`,
{
silent: true,
}
)
).stdout
);
expect(resWithoutTarget.tasks).toEqual([]);
compareTwoArrays(resWithoutTarget.projects, [`${myapp}-e2e`, myapp]);
const resWithTarget = JSON.parse(
(
await runCLIAsync(
`print-affected --files=apps/${myapp}/src/app/app.element.spec.ts --target=test`,
{ silent: true }
)
).stdout.trim()
);
const { runNx } = getPackageManagerCommand();
expect(resWithTarget.tasks[0]).toMatchObject({
id: `${myapp}:test`,
overrides: {},
target: {
project: myapp,
target: 'test',
},
command: `${runNx} run ${myapp}:test`,
outputs: [`coverage/apps/${myapp}`],
});
compareTwoArrays(resWithTarget.projects, [myapp]);
const resWithTargetWithSelect1 = (
await runCLIAsync(
`print-affected --files=apps/${myapp}/src/app/app.element.spec.ts --target=test --select=projects`,
{ silent: true }
)
).stdout.trim();
compareTwoSerializedArrays(resWithTargetWithSelect1, myapp);
const resWithTargetWithSelect2 = (
await runCLIAsync(
`print-affected --files=apps/${myapp}/src/app/app.element.spec.ts --target=test --select="tasks.target.project"`,
{ silent: true }
)
).stdout.trim();
compareTwoSerializedArrays(resWithTargetWithSelect2, myapp);
}, 120000);
function compareTwoSerializedArrays(a: string, b: string) {
compareTwoArrays(
a.split(',').map((_) => _.trim()),
b.split(',').map((_) => _.trim())
);
}
function compareTwoArrays(a: string[], b: string[]) {
expect(a.sort((x, y) => x.localeCompare(y))).toEqual(
b.sort((x, y) => x.localeCompare(y))
);
}
});
|
2,000 | 0 | petrpan-code/nrwl/nx/e2e/nx-run | petrpan-code/nrwl/nx/e2e/nx-run/src/cache.test.ts | import {
cleanupProject,
directoryExists,
listFiles,
newProject,
readFile,
rmDist,
runCLI,
setMaxWorkers,
tmpProjPath,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('cache', () => {
beforeEach(() => newProject());
afterEach(() => cleanupProject());
it('should cache command execution', async () => {
const myapp1 = uniq('myapp1');
const myapp2 = uniq('myapp2');
runCLI(`generate @nx/web:app ${myapp1}`);
setMaxWorkers(join('apps', myapp1, 'project.json'));
runCLI(`generate @nx/web:app ${myapp2}`);
setMaxWorkers(join('apps', myapp2, 'project.json'));
// run build with caching
// --------------------------------------------
const buildAppsCommand = `run-many --target build --projects ${[
myapp1,
myapp2,
].join()}`;
const outputThatPutsDataIntoCache = runCLI(buildAppsCommand);
const filesApp1 = listFiles(`dist/apps/${myapp1}`);
const filesApp2 = listFiles(`dist/apps/${myapp2}`);
// now the data is in cache
expect(outputThatPutsDataIntoCache).not.toContain(
'read the output from the cache'
);
rmDist();
const outputWithBothBuildTasksCached = runCLI(buildAppsCommand);
expect(outputWithBothBuildTasksCached).toContain(
'read the output from the cache'
);
expectCached(outputWithBothBuildTasksCached, [myapp1, myapp2]);
expect(listFiles(`dist/apps/${myapp1}`)).toEqual(filesApp1);
expect(listFiles(`dist/apps/${myapp2}`)).toEqual(filesApp2);
// run with skipping cache
const outputWithBothBuildTasksCachedButSkipped = runCLI(
buildAppsCommand + ' --skip-nx-cache'
);
expect(outputWithBothBuildTasksCachedButSkipped).not.toContain(
`read the output from the cache`
);
// touch myapp1
// --------------------------------------------
updateFile(`apps/${myapp1}/src/main.ts`, (c) => {
return `${c}\n//some comment`;
});
const outputWithBuildApp2Cached = runCLI(buildAppsCommand);
expect(outputWithBuildApp2Cached).toContain(
'read the output from the cache'
);
expectCached(outputWithBuildApp2Cached, [myapp2]);
// touch package.json
// --------------------------------------------
updateFile(`nx.json`, (c) => {
const r = JSON.parse(c);
r.affected = { defaultBase: 'different' };
return JSON.stringify(r);
});
const outputWithNoBuildCached = runCLI(buildAppsCommand);
expect(outputWithNoBuildCached).not.toContain(
'read the output from the cache'
);
// build individual project with caching
const individualBuildWithCache = runCLI(`build ${myapp1}`);
expect(individualBuildWithCache).toContain('local cache');
// skip caching when building individual projects
const individualBuildWithSkippedCache = runCLI(
`build ${myapp1} --skip-nx-cache`
);
expect(individualBuildWithSkippedCache).not.toContain('local cache');
// run lint with caching
// --------------------------------------------
let lintAppsCommand = `run-many --target lint --projects ${[
myapp1,
myapp2,
`${myapp1}-e2e`,
`${myapp2}-e2e`,
].join()}`;
const outputWithNoLintCached = runCLI(lintAppsCommand);
expect(outputWithNoLintCached).not.toContain(
'read the output from the cache'
);
const outputWithBothLintTasksCached = runCLI(lintAppsCommand);
expect(outputWithBothLintTasksCached).toContain(
'read the output from the cache'
);
expectMatchedOutput(outputWithBothLintTasksCached, [
myapp1,
myapp2,
`${myapp1}-e2e`,
`${myapp2}-e2e`,
]);
// run without caching
// --------------------------------------------
// disable caching
// --------------------------------------------
const originalNxJson = readFile('nx.json');
updateFile('nx.json', (c) => {
const nxJson = JSON.parse(c);
for (const key in nxJson.targetDefaults ?? {}) {
delete nxJson.targetDefaults[key].cache;
}
return JSON.stringify(nxJson, null, 2);
});
const outputWithoutCachingEnabled1 = runCLI(buildAppsCommand);
expect(outputWithoutCachingEnabled1).not.toContain(
'read the output from the cache'
);
const outputWithoutCachingEnabled2 = runCLI(buildAppsCommand);
expect(outputWithoutCachingEnabled2).not.toContain(
'read the output from the cache'
);
// re-enable caching after test
// --------------------------------------------
updateFile('nx.json', (c) => originalNxJson);
}, 120000);
it('should support using globs as outputs', async () => {
const mylib = uniq('mylib');
runCLI(`generate @nx/js:library ${mylib}`);
updateJson(join('libs', mylib, 'project.json'), (c) => {
c.targets.build = {
executor: 'nx:run-commands',
outputs: ['{workspaceRoot}/dist/!(.next)/**/!(z|x).(txt|md)'],
options: {
commands: [
'rm -rf dist',
'mkdir dist',
'mkdir dist/apps',
'mkdir dist/.next',
'echo a > dist/apps/a.txt',
'echo b > dist/apps/b.txt',
'echo c > dist/apps/c.txt',
'echo d > dist/apps/d.txt',
'echo e > dist/apps/e.txt',
'echo f > dist/apps/f.md',
'echo g > dist/apps/g.html',
'echo h > dist/.next/h.txt',
'echo x > dist/apps/x.txt',
'echo z > dist/apps/z.md',
],
parallel: false,
},
};
return c;
});
// Run without cache
const runWithoutCache = runCLI(`build ${mylib}`);
expect(runWithoutCache).not.toContain('read the output from the cache');
// Rerun without touching anything
const rerunWithUntouchedOutputs = runCLI(`build ${mylib}`);
expect(rerunWithUntouchedOutputs).toContain('local cache');
const outputsWithUntouchedOutputs = [
...listFiles('dist/apps'),
...listFiles('dist/.next').map((f) => `.next/${f}`),
];
expect(outputsWithUntouchedOutputs).toContain('a.txt');
expect(outputsWithUntouchedOutputs).toContain('b.txt');
expect(outputsWithUntouchedOutputs).toContain('c.txt');
expect(outputsWithUntouchedOutputs).toContain('d.txt');
expect(outputsWithUntouchedOutputs).toContain('e.txt');
expect(outputsWithUntouchedOutputs).toContain('f.md');
expect(outputsWithUntouchedOutputs).toContain('g.html');
expect(outputsWithUntouchedOutputs).toContain('.next/h.txt');
expect(outputsWithUntouchedOutputs).toContain('x.txt');
expect(outputsWithUntouchedOutputs).toContain('z.md');
// Create a file in the dist that does not match output glob
updateFile('dist/apps/c.ts', '');
// Rerun
const rerunWithNewUnrelatedFile = runCLI(`build ${mylib}`);
expect(rerunWithNewUnrelatedFile).toContain('local cache');
const outputsAfterAddingUntouchedFileAndRerunning = [
...listFiles('dist/apps'),
...listFiles('dist/.next').map((f) => `.next/${f}`),
];
expect(outputsAfterAddingUntouchedFileAndRerunning).toContain('a.txt');
expect(outputsAfterAddingUntouchedFileAndRerunning).toContain('b.txt');
expect(outputsAfterAddingUntouchedFileAndRerunning).toContain('c.txt');
expect(outputsAfterAddingUntouchedFileAndRerunning).toContain('d.txt');
expect(outputsAfterAddingUntouchedFileAndRerunning).toContain('e.txt');
expect(outputsAfterAddingUntouchedFileAndRerunning).toContain('f.md');
expect(outputsAfterAddingUntouchedFileAndRerunning).toContain('g.html');
expect(outputsAfterAddingUntouchedFileAndRerunning).toContain(
'.next/h.txt'
);
expect(outputsAfterAddingUntouchedFileAndRerunning).toContain('x.txt');
expect(outputsAfterAddingUntouchedFileAndRerunning).toContain('z.md');
expect(outputsAfterAddingUntouchedFileAndRerunning).toContain('c.ts');
// Clear Dist
rmDist();
// Rerun
const rerunWithoutOutputs = runCLI(`build ${mylib}`);
expect(rerunWithoutOutputs).toContain('read the output from the cache');
const outputsWithoutOutputs = listFiles('dist/apps');
expect(directoryExists(`${tmpProjPath()}/dist/.next`)).toBe(false);
expect(outputsWithoutOutputs).toContain('a.txt');
expect(outputsWithoutOutputs).toContain('b.txt');
expect(outputsWithoutOutputs).toContain('c.txt');
expect(outputsWithoutOutputs).toContain('d.txt');
expect(outputsWithoutOutputs).toContain('e.txt');
expect(outputsWithoutOutputs).toContain('f.md');
expect(outputsWithoutOutputs).not.toContain('c.ts');
expect(outputsWithoutOutputs).not.toContain('g.html');
expect(outputsWithoutOutputs).not.toContain('x.txt');
expect(outputsWithoutOutputs).not.toContain('z.md');
});
it('should use consider filesets when hashing', async () => {
const parent = uniq('parent');
const child1 = uniq('child1');
const child2 = uniq('child2');
runCLI(`generate @nx/js:lib ${parent}`);
runCLI(`generate @nx/js:lib ${child1}`);
runCLI(`generate @nx/js:lib ${child2}`);
updateJson(`nx.json`, (c) => {
c.namedInputs = {
default: ['{projectRoot}/**/*'],
prod: ['!{projectRoot}/**/*.spec.ts'],
};
c.targetDefaults = {
test: {
inputs: ['default', '^prod'],
cache: true,
},
};
return c;
});
updateJson(`libs/${parent}/project.json`, (c) => {
c.implicitDependencies = [child1, child2];
return c;
});
updateJson(`libs/${child1}/project.json`, (c) => {
c.namedInputs = { prod: ['{projectRoot}/**/*.ts'] };
return c;
});
const firstRun = runCLI(`test ${parent}`);
expect(firstRun).not.toContain('read the output from the cache');
// -----------------------------------------
// change child2 spec
updateFile(`libs/${child2}/src/lib/${child2}.spec.ts`, (c) => {
return c + '\n// some change';
});
const child2RunSpecChange = runCLI(`test ${child2}`);
expect(child2RunSpecChange).not.toContain('read the output from the cache');
const parentRunSpecChange = runCLI(`test ${parent}`);
expect(parentRunSpecChange).toContain('read the output from the cache');
// -----------------------------------------
// change child2 prod
updateFile(`libs/${child2}/src/lib/${child2}.ts`, (c) => {
return c + '\n// some change';
});
const child2RunProdChange = runCLI(`test ${child2}`);
expect(child2RunProdChange).not.toContain('read the output from the cache');
const parentRunProdChange = runCLI(`test ${parent}`);
expect(parentRunProdChange).not.toContain('read the output from the cache');
// -----------------------------------------
// change child1 spec
updateFile(`libs/${child1}/src/lib/${child1}.spec.ts`, (c) => {
return c + '\n// some change';
});
// this is a miss cause child1 redefined "prod" to include all files
const parentRunSpecChangeChild1 = runCLI(`test ${parent}`);
expect(parentRunSpecChangeChild1).not.toContain(
'read the output from the cache'
);
}, 120000);
it('should support ENV as an input', () => {
const lib = uniq('lib');
runCLI(`generate @nx/js:lib ${lib}`);
updateJson(`nx.json`, (c) => {
c.targetDefaults = {
echo: {
cache: true,
inputs: [
{
env: 'NAME',
},
],
},
};
return c;
});
updateJson(`libs/${lib}/project.json`, (c) => {
c.targets = {
echo: {
command: 'echo $NAME',
},
};
return c;
});
const firstRun = runCLI(`echo ${lib}`, {
env: { NAME: 'e2e' },
});
expect(firstRun).not.toContain('read the output from the cache');
const secondRun = runCLI(`echo ${lib}`, {
env: { NAME: 'e2e' },
});
expect(secondRun).toContain('read the output from the cache');
const thirdRun = runCLI(`echo ${lib}`, {
env: { NAME: 'change' },
});
expect(thirdRun).not.toContain('read the output from the cache');
const fourthRun = runCLI(`echo ${lib}`, {
env: { NAME: 'change' },
});
expect(fourthRun).toContain('read the output from the cache');
}, 120000);
function expectCached(
actualOutput: string,
expectedCachedProjects: string[]
) {
expectProjectMatchTaskCacheStatus(actualOutput, expectedCachedProjects);
}
function expectMatchedOutput(
actualOutput: string,
expectedMatchedOutputProjects: string[]
) {
expectProjectMatchTaskCacheStatus(
actualOutput,
expectedMatchedOutputProjects,
'existing outputs match the cache'
);
}
function expectProjectMatchTaskCacheStatus(
actualOutput: string,
expectedProjects: string[],
cacheStatus: string = 'local cache'
) {
const matchingProjects = [];
const lines = actualOutput.split('\n');
lines.forEach((s) => {
if (s.trimStart().startsWith(`> nx run`)) {
const projectName = s
.trimStart()
.split(`> nx run `)[1]
.split(':')[0]
.trim();
if (s.indexOf(cacheStatus) > -1) {
matchingProjects.push(projectName);
}
}
});
matchingProjects.sort((a, b) => a.localeCompare(b));
expectedProjects.sort((a, b) => a.localeCompare(b));
expect(matchingProjects).toEqual(expectedProjects);
}
});
|
2,001 | 0 | petrpan-code/nrwl/nx/e2e/nx-run | petrpan-code/nrwl/nx/e2e/nx-run/src/invoke-runner.test.ts | import {
cleanupProject,
newProject,
runCLI,
runCommand,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('Invoke Runner', () => {
let proj: string;
beforeAll(() => (proj = newProject()));
afterAll(() => cleanupProject());
it('should invoke runner imperatively ', async () => {
const mylib = uniq('mylib');
runCLI(`generate @nx/js:lib ${mylib}`);
updateJson(join('libs', mylib, 'project.json'), (c) => {
c.targets['prebuild'] = {
command: 'echo prebuild',
};
c.targets['build'] = {
command: 'echo build',
};
return c;
});
updateFile(
'runner.js',
`
const { initTasksRunner } = require('nx/src/index');
async function main(){
const r = await initTasksRunner({});
await r.invoke({tasks: [{id: '${mylib}:prebuild', target: {project: '${mylib}', target: 'prebuild'}, outputs: [], overrides: {__overrides_unparsed__: ''}}]});
await r.invoke({tasks: [{id: '${mylib}:build', target: {project: '${mylib}', target: 'build'}, outputs: [], overrides: {__overrides_unparsed__: ''}}]});
}
main().then(q => {
console.log("DONE")
process.exit(0)
})
`
);
const q = runCommand('node runner.js');
expect(q).toContain(`Task ${mylib}:prebuild`);
expect(q).toContain(`Task ${mylib}:build`);
expect(q).toContain(`Successfully ran 1 tasks`);
expect(q).toContain(`DONE`);
});
});
|
2,002 | 0 | petrpan-code/nrwl/nx/e2e/nx-run | petrpan-code/nrwl/nx/e2e/nx-run/src/nx-cloud.test.ts | import { cleanupProject, newProject, runCLI } from '@nx/e2e/utils';
describe('Nx Cloud', () => {
beforeAll(() =>
newProject({
unsetProjectNameAndRootFormat: false,
})
);
const libName = 'test-lib';
beforeAll(() => {
runCLI('connect --no-interactive', {
env: {
NX_CLOUD_API: 'https://staging.nx.app',
},
});
runCLI(`generate @nx/js:lib ${libName} --no-interactive`);
});
afterAll(() => cleanupProject());
it('should cache tests', async () => {
// Should be able to view logs with Nx Cloud
expect(runCLI(`test ${libName}`)).toContain(
`View logs and investigate cache misses at https://staging.nx.app`
);
// Reset Local cache
runCLI(`reset`);
// Should be pull cache from Nx Cloud
expect(runCLI(`test ${libName}`)).toContain(
`Nx Cloud made it possible to reuse test-lib: https://staging.nx.app`
);
});
});
|
2,003 | 0 | petrpan-code/nrwl/nx/e2e/nx-run | petrpan-code/nrwl/nx/e2e/nx-run/src/run.test.ts | import {
checkFilesExist,
cleanupProject,
fileExists,
isWindows,
newProject,
readJson,
removeFile,
runCLI,
runCLIAsync,
runCommand,
setMaxWorkers,
tmpProjPath,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { PackageJson } from 'nx/src/utils/package-json';
import * as path from 'path';
import { join } from 'path';
describe('Nx Running Tests', () => {
let proj: string;
beforeAll(() => (proj = newProject()));
afterAll(() => cleanupProject());
// Ensures that nx.json is restored to its original state after each test
let existingNxJson;
beforeEach(() => {
existingNxJson = readJson('nx.json');
});
afterEach(() => {
updateFile('nx.json', JSON.stringify(existingNxJson, null, 2));
});
describe('running targets', () => {
describe('(forwarding params)', () => {
let proj = uniq('proj');
beforeAll(() => {
runCLI(`generate @nx/js:lib ${proj}`);
updateJson(`libs/${proj}/project.json`, (c) => {
c.targets['echo'] = {
command: 'echo ECHO:',
};
return c;
});
});
it.each([
'--watch false',
'--watch=false',
'--arr=a,b,c',
'--arr=a --arr=b --arr=c',
'a',
'--a.b=1',
'--a.b 1',
'-- a b c --a --a.b=1',
'--ignored -- a b c --a --a.b=1',
])('should forward %s properly', (args) => {
const output = runCLI(`echo ${proj} ${args}`);
expect(output).toContain(`ECHO: ${args.replace(/^.*-- /, '')}`);
});
});
it('should execute long running tasks', () => {
const myapp = uniq('myapp');
runCLI(`generate @nx/web:app ${myapp}`);
updateJson(`apps/${myapp}/project.json`, (c) => {
c.targets['counter'] = {
executor: '@nx/workspace:counter',
options: {
to: 2,
},
};
return c;
});
const success = runCLI(`counter ${myapp} --result=true`);
expect(success).toContain('0');
expect(success).toContain('1');
expect(() => runCLI(`counter ${myapp} --result=false`)).toThrowError();
});
it('should run npm scripts', async () => {
const mylib = uniq('mylib');
runCLI(`generate @nx/node:lib ${mylib}`);
// Used to restore targets to lib after test
const original = readJson(`libs/${mylib}/project.json`);
updateJson(`libs/${mylib}/project.json`, (j) => {
delete j.targets;
return j;
});
updateFile(
`libs/${mylib}/package.json`,
JSON.stringify(<PackageJson>{
name: 'mylib1',
version: '1.0.0',
scripts: { 'echo:dev': `echo ECHOED`, 'echo:fail': 'should not run' },
nx: {
includedScripts: ['echo:dev'],
},
})
);
const { stdout } = await runCLIAsync(
`echo:dev ${mylib} -- positional --a=123 --no-b`,
{
silent: true,
}
);
if (isWindows()) {
expect(stdout).toMatch(/ECHOED "positional" "--a=123" "--no-b"/);
} else {
expect(stdout).toMatch(/ECHOED positional --a=123 --no-b/);
}
expect(runCLI(`echo:fail ${mylib}`, { silenceError: true })).toContain(
`Cannot find configuration for task ${mylib}:echo:fail`
);
updateJson(`libs/${mylib}/project.json`, (c) => original);
}, 1000000);
describe('tokens support', () => {
let app: string;
beforeAll(async () => {
app = uniq('myapp');
runCLI(`generate @nx/web:app ${app}`);
setMaxWorkers(join('apps', app, 'project.json'));
});
it('should support using {projectRoot} in options blocks in project.json', async () => {
updateJson(`apps/${app}/project.json`, (c) => {
c.targets['echo'] = {
command: `node -e 'console.log("{projectRoot}")'`,
};
return c;
});
const output = runCLI(`echo ${app}`);
expect(output).toContain(`apps/${app}`);
});
it('should support using {projectName} in options blocks in project.json', () => {
updateJson(`apps/${app}/project.json`, (c) => {
c.targets['echo'] = {
command: `node -e 'console.log("{projectName}")'`,
};
return c;
});
const output = runCLI(`echo ${app}`);
expect(output).toContain(app);
});
it('should support using {projectRoot} in targetDefaults', async () => {
updateJson(`nx.json`, (json) => {
json.targetDefaults = {
echo: {
command: `node -e 'console.log("{projectRoot}")'`,
},
};
return json;
});
updateJson(`apps/${app}/project.json`, (c) => {
c.targets['echo'] = {};
return c;
});
const output = runCLI(`echo ${app}`);
expect(output).toContain(`apps/${app}`);
});
it('should support using {projectName} in targetDefaults', () => {
updateJson(`nx.json`, (json) => {
json.targetDefaults = {
echo: {
command: `node -e 'console.log("{projectName}")'`,
},
};
return json;
});
updateJson(`apps/${app}/project.json`, (c) => {
c.targets['echo'] = {};
return c;
});
const output = runCLI(`echo ${app}`);
expect(output).toContain(app);
});
});
});
describe('Nx Bail', () => {
it('should stop executing all tasks when one of the tasks fails', async () => {
const myapp1 = uniq('a');
const myapp2 = uniq('b');
runCLI(`generate @nx/web:app ${myapp1}`);
runCLI(`generate @nx/web:app ${myapp2}`);
updateJson(`apps/${myapp1}/project.json`, (c) => {
c.targets['error'] = {
command: 'echo boom1 && exit 1',
};
return c;
});
updateJson(`apps/${myapp2}/project.json`, (c) => {
c.targets['error'] = {
executor: 'nx:run-commands',
options: {
command: 'echo boom2 && exit 1',
},
};
return c;
});
let withoutBail = runCLI(`run-many --target=error --parallel=1`, {
silenceError: true,
})
.split('\n')
.map((r) => r.trim())
.filter((r) => r);
withoutBail = withoutBail.slice(withoutBail.indexOf('Failed tasks:'));
expect(withoutBail).toContain(`- ${myapp1}:error`);
expect(withoutBail).toContain(`- ${myapp2}:error`);
let withBail = runCLI(`run-many --target=error --parallel=1 --nx-bail`, {
silenceError: true,
})
.split('\n')
.map((r) => r.trim())
.filter((r) => r);
withBail = withBail.slice(withBail.indexOf('Failed tasks:'));
expect(withBail.length).toEqual(2);
if (withBail[1] === `- ${myapp1}:error`) {
expect(withBail).not.toContain(`- ${myapp2}:error`);
} else {
expect(withBail[1]).toEqual(`- ${myapp2}:error`);
expect(withBail).not.toContain(`- ${myapp1}:error`);
}
});
});
describe('run-one', () => {
it('should build a specific project', () => {
const myapp = uniq('app');
runCLI(`generate @nx/web:app ${myapp}`);
runCLI(`build ${myapp}`);
}, 10000);
it('should support project name positional arg non-consecutive to target', () => {
const myapp = uniq('app');
runCLI(`generate @nx/web:app ${myapp}`);
runCLI(`build --verbose ${myapp}`);
}, 10000);
it('should run targets from package json', () => {
const myapp = uniq('app');
const target = uniq('script');
const expectedOutput = uniq('myEchoedString');
const expectedEnvOutput = uniq('myEnvString');
runCLI(`generate @nx/web:app ${myapp}`);
updateFile(
`apps/${myapp}/package.json`,
JSON.stringify({
name: myapp,
scripts: {
[target]: `echo ${expectedOutput} $ENV_VAR`,
},
nx: {
targets: {
[target]: {
configurations: {
production: {},
},
},
},
},
})
);
updateFile(
`apps/${myapp}/.env.production`,
`ENV_VAR=${expectedEnvOutput}`
);
expect(runCLI(`${target} ${myapp}`)).toContain(expectedOutput);
expect(runCLI(`${target} ${myapp}`)).not.toContain(expectedEnvOutput);
expect(runCLI(`${target} ${myapp} --configuration production`)).toContain(
expectedEnvOutput
);
}, 10000);
it('should run targets inferred from plugin-specified project files', () => {
// Setup an app to extend
const myapp = uniq('app');
runCLI(`generate @nx/web:app ${myapp}`);
// Register an Nx plugin
const plugin = `module.exports = {
projectFilePatterns: ['inferred-project.nxproject'],
registerProjectTargets: () => ({
"echo": {
"executor": "nx:run-commands",
"options": {
"command": "echo inferred-target"
}
}
})
}`;
updateFile('tools/local-plugin/plugin.js', plugin);
updateFile('nx.json', (c) => {
const nxJson = JSON.parse(c);
nxJson.plugins = ['./tools/local-plugin/plugin.js'];
return JSON.stringify(nxJson, null, 2);
});
// Create a custom project file for the app
updateFile(`apps/${myapp}/inferred-project.nxproject`, 'contents');
expect(runCLI(`echo ${myapp}`)).toContain('inferred-target');
});
it('should build a specific project with the daemon disabled', () => {
const myapp = uniq('app');
runCLI(`generate @nx/web:app ${myapp}`);
const buildWithDaemon = runCLI(`build ${myapp}`, {
env: { NX_DAEMON: 'false' },
});
expect(buildWithDaemon).toContain('Successfully ran target build');
const buildAgain = runCLI(`build ${myapp}`, {
env: { NX_DAEMON: 'false' },
});
expect(buildAgain).toContain('[local cache]');
}, 10000);
it('should build the project when within the project root', () => {
const myapp = uniq('app');
runCLI(`generate @nx/web:app ${myapp}`);
// Should work within the project directory
expect(runCommand(`cd apps/${myapp}/src && npx nx build`)).toContain(
`nx run ${myapp}:build:production`
);
}, 10000);
describe('target defaults + executor specifications', () => {
it('should be able to run targets with unspecified executor given an appropriate targetDefaults entry', () => {
const target = uniq('target');
const lib = uniq('lib');
updateJson('nx.json', (nxJson) => {
nxJson.targetDefaults ??= {};
nxJson.targetDefaults[target] = {
executor: 'nx:run-commands',
options: {
command: `echo Hello from ${target}`,
},
};
return nxJson;
});
updateFile(
`libs/${lib}/project.json`,
JSON.stringify({
name: lib,
targets: {
[target]: {},
},
})
);
expect(runCLI(`${target} ${lib} --verbose`)).toContain(
`Hello from ${target}`
);
});
it('should be able to pull options from targetDefaults based on executor', () => {
const target = uniq('target');
const lib = uniq('lib');
updateJson('nx.json', (nxJson) => {
nxJson.targetDefaults ??= {};
nxJson.targetDefaults[`nx:run-commands`] = {
options: {
command: `echo Hello from ${target}`,
},
};
return nxJson;
});
updateFile(
`libs/${lib}/project.json`,
JSON.stringify({
name: lib,
targets: {
[target]: {
executor: 'nx:run-commands',
},
},
})
);
expect(runCLI(`${target} ${lib} --verbose`)).toContain(
`Hello from ${target}`
);
});
});
describe('target dependencies', () => {
let myapp;
let mylib1;
let mylib2;
beforeAll(() => {
myapp = uniq('myapp');
mylib1 = uniq('mylib1');
mylib2 = uniq('mylib1');
runCLI(`generate @nx/web:app ${myapp}`);
runCLI(`generate @nx/js:lib ${mylib1}`);
runCLI(`generate @nx/js:lib ${mylib2}`);
updateFile(
`apps/${myapp}/src/main.ts`,
`
import "@${proj}/${mylib1}";
import "@${proj}/${mylib2}";
`
);
});
it('should be able to include deps using dependsOn', async () => {
const originalWorkspace = readJson(`apps/${myapp}/project.json`);
updateJson(`apps/${myapp}/project.json`, (config) => {
config.targets.prep = {
executor: 'nx:run-commands',
options: {
command: 'echo PREP',
},
};
config.targets.build.dependsOn = ['prep', '^build'];
return config;
});
const output = runCLI(`build ${myapp}`);
expect(output).toContain(
`NX Running target build for project ${myapp} and 3 tasks it depends on`
);
expect(output).toContain(myapp);
expect(output).toContain(mylib1);
expect(output).toContain(mylib2);
expect(output).toContain('PREP');
updateJson(`apps/${myapp}/project.json`, () => originalWorkspace);
}, 10000);
it('should be able to include deps using target defaults defined at the root', async () => {
const nxJson = readJson('nx.json');
updateJson(`apps/${myapp}/project.json`, (config) => {
config.targets.prep = {
command: 'echo PREP > one.txt',
};
config.targets.outside = {
command: 'echo OUTSIDE',
};
return config;
});
nxJson.targetDefaults = {
prep: {
outputs: ['{workspaceRoot}/one.txt'],
cache: true,
},
outside: {
dependsOn: ['prep'],
cache: true,
},
};
updateFile('nx.json', JSON.stringify(nxJson));
const output = runCLI(`outside ${myapp}`);
expect(output).toContain(
`NX Running target outside for project ${myapp} and 1 task it depends on`
);
removeFile(`one.txt`);
runCLI(`outside ${myapp}`);
checkFilesExist(`one.txt`);
}, 10000);
});
});
describe('run-many', () => {
it('should build specific and all projects', () => {
// This is required to ensure the numbers used in the assertions make sense for this test
const proj = newProject();
const appA = uniq('appa-rand');
const libA = uniq('liba-rand');
const libB = uniq('libb-rand');
const libC = uniq('libc-rand');
const libD = uniq('libd-rand');
runCLI(`generate @nx/web:app ${appA}`);
runCLI(`generate @nx/js:lib ${libA} --bundler=tsc --defaults`);
runCLI(
`generate @nx/js:lib ${libB} --bundler=tsc --defaults --tags=ui-a`
);
runCLI(
`generate @nx/js:lib ${libC} --bundler=tsc --defaults --tags=ui-b,shared`
);
runCLI(`generate @nx/node:lib ${libD} --defaults --tags=api`);
// libA depends on libC
updateFile(
`libs/${libA}/src/lib/${libA}.spec.ts`,
`
import '@${proj}/${libC}';
describe('sample test', () => {
it('should test', () => {
expect(1).toEqual(1);
});
});
`
);
// testing run many starting'
const buildParallel = runCLI(
`run-many --target=build --projects="${libC},${libB}"`
);
expect(buildParallel).toContain(`Running target build for 2 projects:`);
expect(buildParallel).not.toContain(`- ${appA}`);
expect(buildParallel).not.toContain(`- ${libA}`);
expect(buildParallel).toContain(`- ${libB}`);
expect(buildParallel).toContain(`- ${libC}`);
expect(buildParallel).not.toContain(`- ${libD}`);
expect(buildParallel).toContain('Successfully ran target build');
// testing run many --all starting
const buildAllParallel = runCLI(`run-many --target=build`);
expect(buildAllParallel).toContain(
`Running target build for 4 projects:`
);
expect(buildAllParallel).toContain(`- ${appA}`);
expect(buildAllParallel).toContain(`- ${libA}`);
expect(buildAllParallel).toContain(`- ${libB}`);
expect(buildAllParallel).toContain(`- ${libC}`);
expect(buildAllParallel).not.toContain(`- ${libD}`);
expect(buildAllParallel).toContain('Successfully ran target build');
// testing run many by tags
const buildByTagParallel = runCLI(
`run-many --target=build --projects="tag:ui*"`
);
expect(buildByTagParallel).toContain(
`Running target build for 2 projects:`
);
expect(buildByTagParallel).not.toContain(`- ${appA}`);
expect(buildByTagParallel).not.toContain(`- ${libA}`);
expect(buildByTagParallel).toContain(`- ${libB}`);
expect(buildByTagParallel).toContain(`- ${libC}`);
expect(buildByTagParallel).not.toContain(`- ${libD}`);
expect(buildByTagParallel).toContain('Successfully ran target build');
// testing run many with exclude
const buildWithExcludeParallel = runCLI(
`run-many --target=build --exclude="${libD},tag:ui*"`
);
expect(buildWithExcludeParallel).toContain(
`Running target build for 2 projects and 1 task they depend on:`
);
expect(buildWithExcludeParallel).toContain(`- ${appA}`);
expect(buildWithExcludeParallel).toContain(`- ${libA}`);
expect(buildWithExcludeParallel).not.toContain(`- ${libB}`);
expect(buildWithExcludeParallel).toContain(`${libC}`); // should still include libC as dependency despite exclude
expect(buildWithExcludeParallel).not.toContain(`- ${libD}`);
expect(buildWithExcludeParallel).toContain(
'Successfully ran target build'
);
// testing run many when project depends on other projects
const buildWithDeps = runCLI(
`run-many --target=build --projects="${libA}"`
);
expect(buildWithDeps).toContain(
`Running target build for project ${libA} and 1 task it depends on:`
);
expect(buildWithDeps).not.toContain(`- ${appA}`);
expect(buildWithDeps).toContain(`- ${libA}`);
expect(buildWithDeps).toContain(`${libC}`); // build should include libC as dependency
expect(buildWithDeps).not.toContain(`- ${libB}`);
expect(buildWithDeps).not.toContain(`- ${libD}`);
expect(buildWithDeps).toContain('Successfully ran target build');
// testing run many --configuration
const buildConfig = runCLI(
`run-many --target=build --projects="${appA},${libA}" --prod`
);
expect(buildConfig).toContain(
`Running target build for 2 projects and 1 task they depend on:`
);
expect(buildConfig).toContain(`run ${appA}:build:production`);
expect(buildConfig).toContain(`run ${libA}:build`);
expect(buildConfig).toContain(`run ${libC}:build`);
expect(buildConfig).toContain('Successfully ran target build');
// testing run many with daemon disabled
const buildWithDaemon = runCLI(`run-many --target=build`, {
env: { NX_DAEMON: 'false' },
});
expect(buildWithDaemon).toContain(`Successfully ran target build`);
}, 1000000);
it('should run multiple targets', () => {
const myapp1 = uniq('myapp');
const myapp2 = uniq('myapp');
runCLI(`generate @nx/web:app ${myapp1}`);
runCLI(`generate @nx/web:app ${myapp2}`);
let outputs = runCLI(
// Options with lists can be specified using multiple args or with a delimiter (comma or space).
`run-many -t build -t test -p ${myapp1} ${myapp2} --ci`
);
expect(outputs).toContain('Running targets build, test for 2 projects:');
outputs = runCLI(`run-many -t build test -p=${myapp1},${myapp2}`);
expect(outputs).toContain('Running targets build, test for 2 projects:');
});
});
describe('exec', () => {
let pkg: string;
let pkg2: string;
let pkgRoot: string;
let pkg2Root: string;
let originalRootPackageJson: PackageJson;
beforeAll(() => {
originalRootPackageJson = readJson<PackageJson>('package.json');
pkg = uniq('package');
pkg2 = uniq('package');
pkgRoot = tmpProjPath(path.join('libs', pkg));
pkg2Root = tmpProjPath(path.join('libs', pkg2));
runCLI(`generate @nx/js:lib ${pkg} --bundler=none --unitTestRunner=none`);
runCLI(
`generate @nx/js:lib ${pkg2} --bundler=none --unitTestRunner=none`
);
updateJson<PackageJson>('package.json', (v) => {
v.workspaces = ['libs/*'];
return v;
});
updateFile(
`libs/${pkg}/package.json`,
JSON.stringify(<PackageJson>{
name: pkg,
version: '0.0.1',
scripts: {
build: 'nx exec -- echo HELLO',
'build:option': 'nx exec -- echo HELLO WITH OPTION',
},
})
);
updateFile(
`libs/${pkg2}/package.json`,
JSON.stringify(<PackageJson>{
name: pkg2,
version: '0.0.1',
scripts: {
build: "nx exec -- echo '$NX_PROJECT_NAME'",
},
})
);
updateJson(`libs/${pkg2}/project.json`, (content) => {
content['implicitDependencies'] = [pkg];
return content;
});
});
afterAll(() => {
updateJson('package.json', () => originalRootPackageJson);
});
it('should work for npm scripts', () => {
const output = runCommand('npm run build', {
cwd: pkgRoot,
});
expect(output).toContain('HELLO');
expect(output).toContain(`nx run ${pkg}:build`);
});
it('should run adhoc tasks in topological order', () => {
let output = runCLI('exec -- echo HELLO');
expect(output).toContain('HELLO');
output = runCLI(`build ${pkg}`);
expect(output).toContain(pkg);
expect(output).not.toContain(pkg2);
output = runCommand('npm run build', {
cwd: pkgRoot,
});
expect(output).toContain(pkg);
expect(output).not.toContain(pkg2);
output = runCLI(`exec -- echo '$NX_PROJECT_NAME'`).replace(/\s+/g, ' ');
expect(output).toContain(pkg);
expect(output).toContain(pkg2);
output = runCLI("exec -- echo '$NX_PROJECT_ROOT_PATH'").replace(
/\s+/g,
' '
);
expect(output).toContain(`${path.join('libs', pkg)}`);
expect(output).toContain(`${path.join('libs', pkg2)}`);
output = runCLI(`exec --projects ${pkg} -- echo WORLD`);
expect(output).toContain('WORLD');
output = runCLI(`exec --projects ${pkg} -- echo '$NX_PROJECT_NAME'`);
expect(output).toContain(pkg);
expect(output).not.toContain(pkg2);
});
it('should work for npm scripts with delimiter', () => {
const output = runCommand('npm run build:option', { cwd: pkgRoot });
expect(output).toContain('HELLO WITH OPTION');
expect(output).toContain(`nx run ${pkg}:"build:option"`);
});
it('should pass overrides', () => {
const output = runCommand('npm run build WORLD', {
cwd: pkgRoot,
});
expect(output).toContain('HELLO WORLD');
});
describe('caching', () => {
it('shoud cache subsequent calls', () => {
runCommand('npm run build', {
cwd: pkgRoot,
});
const output = runCommand('npm run build', {
cwd: pkgRoot,
});
expect(output).toContain('Nx read the output from the cache');
});
it('should read outputs', () => {
const nodeCommands = [
"const fs = require('fs')",
"fs.mkdirSync('../../tmp/exec-outputs-test', {recursive: true})",
"fs.writeFileSync('../../tmp/exec-outputs-test/file.txt', 'Outputs')",
];
updateFile(
`libs/${pkg}/package.json`,
JSON.stringify(<PackageJson>{
name: pkg,
version: '0.0.1',
scripts: {
build: `nx exec -- node -e "${nodeCommands.join(';')}"`,
},
nx: {
targets: {
build: {
outputs: ['{workspaceRoot}/tmp/exec-outputs-test'],
},
},
},
})
);
runCommand('npm run build', {
cwd: pkgRoot,
});
expect(
fileExists(tmpProjPath('tmp/exec-outputs-test/file.txt'))
).toBeTruthy();
removeFile('tmp');
const output = runCommand('npm run build', {
cwd: pkgRoot,
});
expect(output).toContain('[local cache]');
expect(
fileExists(tmpProjPath('tmp/exec-outputs-test/file.txt'))
).toBeTruthy();
});
});
});
});
|
2,008 | 0 | petrpan-code/nrwl/nx/e2e/playwright | petrpan-code/nrwl/nx/e2e/playwright/src/playwright.test.ts | import {
cleanupProject,
newProject,
uniq,
runCLI,
ensurePlaywrightBrowsersInstallation,
getPackageManagerCommand,
getSelectedPackageManager,
} from '@nx/e2e/utils';
const TEN_MINS_MS = 600_000;
describe('Playwright E2E Test runner', () => {
const pmc = getPackageManagerCommand({
packageManager: getSelectedPackageManager(),
});
beforeAll(() => {
newProject({ name: uniq('playwright') });
});
afterAll(() => cleanupProject());
it(
'should test and lint example app',
() => {
ensurePlaywrightBrowsersInstallation();
runCLI(
`g @nx/web:app demo-e2e --unitTestRunner=none --bundler=vite --e2eTestRunner=none --style=css --no-interactive`
);
runCLI(
`g @nx/playwright:configuration --project demo-e2e --webServerCommand="${pmc.runNx} serve demo-e2e" --webServerAddress="http://localhost:4200"`
);
const e2eResults = runCLI(`e2e demo-e2e`);
expect(e2eResults).toContain('Successfully ran target e2e for project');
const lintResults = runCLI(`lint demo-e2e`);
expect(lintResults).toContain('All files pass linting');
},
TEN_MINS_MS
);
it(
'should test and lint example app with js',
() => {
ensurePlaywrightBrowsersInstallation();
runCLI(
`g @nx/web:app demo-js-e2e --unitTestRunner=none --bundler=vite --e2eTestRunner=none --style=css --no-interactive`
);
runCLI(
`g @nx/playwright:configuration --project demo-js-e2e --js --webServerCommand="${pmc.runNx} serve demo-e2e" --webServerAddress="http://localhost:4200"`
);
const e2eResults = runCLI(`e2e demo-js-e2e`);
expect(e2eResults).toContain('Successfully ran target e2e for project');
const lintResults = runCLI(`lint demo-e2e`);
expect(lintResults).toContain('All files pass linting');
},
TEN_MINS_MS
);
});
|
2,014 | 0 | petrpan-code/nrwl/nx/e2e/plugin | petrpan-code/nrwl/nx/e2e/plugin/src/nx-plugin.test.ts | import { ProjectConfiguration } from '@nx/devkit';
import {
checkFilesExist,
cleanupProject,
createFile,
expectTestsPass,
getPackageManagerCommand,
newProject,
readJson,
runCLI,
runCLIAsync,
runCommand,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import type { PackageJson } from 'nx/src/utils/package-json';
import {
ASYNC_GENERATOR_EXECUTOR_CONTENTS,
NX_PLUGIN_V2_CONTENTS,
} from './nx-plugin.fixtures';
import { join } from 'path';
describe('Nx Plugin', () => {
let workspaceName: string;
beforeAll(() => {
workspaceName = newProject();
});
afterAll(() => cleanupProject());
it('should be able to generate a Nx Plugin ', async () => {
const plugin = uniq('plugin');
runCLI(
`generate @nx/plugin:plugin ${plugin} --linter=eslint --e2eTestRunner=jest --publishable`
);
const lintResults = runCLI(`lint ${plugin}`);
expect(lintResults).toContain('All files pass linting.');
const buildResults = runCLI(`build ${plugin}`);
expect(buildResults).toContain('Done compiling TypeScript files');
checkFilesExist(
`dist/libs/${plugin}/package.json`,
`dist/libs/${plugin}/src/index.js`
);
const project = readJson(`libs/${plugin}/project.json`);
expect(project).toMatchObject({
tags: [],
});
runCLI(`e2e ${plugin}-e2e`);
}, 90000);
it('should be able to generate a migration', async () => {
const plugin = uniq('plugin');
const version = '1.0.0';
runCLI(`generate @nx/plugin:plugin ${plugin} --linter=eslint`);
runCLI(
`generate @nx/plugin:migration --project=${plugin} --packageVersion=${version} --packageJsonUpdates=false`
);
const lintResults = runCLI(`lint ${plugin}`);
expect(lintResults).toContain('All files pass linting.');
expectTestsPass(await runCLIAsync(`test ${plugin}`));
const buildResults = runCLI(`build ${plugin}`);
expect(buildResults).toContain('Done compiling TypeScript files');
checkFilesExist(
`dist/libs/${plugin}/src/migrations/update-${version}/update-${version}.js`,
`libs/${plugin}/src/migrations/update-${version}/update-${version}.ts`
);
const migrationsJson = readJson(`libs/${plugin}/migrations.json`);
expect(migrationsJson).toMatchObject({
generators: expect.objectContaining({
[`update-${version}`]: {
version,
description: `Migration for v1.0.0`,
implementation: `./src/migrations/update-${version}/update-${version}`,
},
}),
});
}, 90000);
it('should be able to generate a generator', async () => {
const plugin = uniq('plugin');
const generator = uniq('generator');
runCLI(`generate @nx/plugin:plugin ${plugin} --linter=eslint`);
runCLI(`generate @nx/plugin:generator ${generator} --project=${plugin}`);
const lintResults = runCLI(`lint ${plugin}`);
expect(lintResults).toContain('All files pass linting.');
expectTestsPass(await runCLIAsync(`test ${plugin}`));
const buildResults = runCLI(`build ${plugin}`);
expect(buildResults).toContain('Done compiling TypeScript files');
checkFilesExist(
`libs/${plugin}/src/generators/${generator}/schema.d.ts`,
`libs/${plugin}/src/generators/${generator}/schema.json`,
`libs/${plugin}/src/generators/${generator}/generator.ts`,
`libs/${plugin}/src/generators/${generator}/generator.spec.ts`,
`dist/libs/${plugin}/src/generators/${generator}/schema.d.ts`,
`dist/libs/${plugin}/src/generators/${generator}/schema.json`,
`dist/libs/${plugin}/src/generators/${generator}/generator.js`
);
const generatorJson = readJson(`libs/${plugin}/generators.json`);
expect(generatorJson).toMatchObject({
generators: expect.objectContaining({
[generator]: {
factory: `./src/generators/${generator}/generator`,
schema: `./src/generators/${generator}/schema.json`,
description: `${generator} generator`,
},
}),
});
}, 90000);
it('should be able to generate an executor', async () => {
const plugin = uniq('plugin');
const executor = uniq('executor');
runCLI(`generate @nx/plugin:plugin ${plugin} --linter=eslint`);
runCLI(
`generate @nx/plugin:executor ${executor} --project=${plugin} --includeHasher`
);
const lintResults = runCLI(`lint ${plugin}`);
expect(lintResults).toContain('All files pass linting.');
expectTestsPass(await runCLIAsync(`test ${plugin}`));
const buildResults = runCLI(`build ${plugin}`);
expect(buildResults).toContain('Done compiling TypeScript files');
checkFilesExist(
`libs/${plugin}/src/executors/${executor}/schema.d.ts`,
`libs/${plugin}/src/executors/${executor}/schema.json`,
`libs/${plugin}/src/executors/${executor}/executor.ts`,
`libs/${plugin}/src/executors/${executor}/hasher.ts`,
`libs/${plugin}/src/executors/${executor}/executor.spec.ts`,
`dist/libs/${plugin}/src/executors/${executor}/schema.d.ts`,
`dist/libs/${plugin}/src/executors/${executor}/schema.json`,
`dist/libs/${plugin}/src/executors/${executor}/executor.js`,
`dist/libs/${plugin}/src/executors/${executor}/hasher.js`
);
const executorsJson = readJson(`libs/${plugin}/executors.json`);
expect(executorsJson).toMatchObject({
executors: expect.objectContaining({
[executor]: {
implementation: `./src/executors/${executor}/executor`,
hasher: `./src/executors/${executor}/hasher`,
schema: `./src/executors/${executor}/schema.json`,
description: `${executor} executor`,
},
}),
});
}, 90000);
it('should catch invalid implementations, schemas, and version in lint', async () => {
const plugin = uniq('plugin');
const goodGenerator = uniq('good-generator');
const goodExecutor = uniq('good-executor');
const badExecutorBadImplPath = uniq('bad-executor');
const goodMigration = uniq('good-migration');
const badFactoryPath = uniq('bad-generator');
const badMigrationVersion = uniq('bad-version');
const missingMigrationVersion = uniq('missing-version');
// Generating the plugin results in a generator also called {plugin},
// as well as an executor called "build"
runCLI(`generate @nx/plugin:plugin ${plugin} --linter=eslint`);
runCLI(
`generate @nx/plugin:generator ${goodGenerator} --project=${plugin}`
);
runCLI(
`generate @nx/plugin:generator ${badFactoryPath} --project=${plugin}`
);
runCLI(`generate @nx/plugin:executor ${goodExecutor} --project=${plugin}`);
runCLI(
`generate @nx/plugin:executor ${badExecutorBadImplPath} --project=${plugin}`
);
runCLI(
`generate @nx/plugin:migration ${badMigrationVersion} --project=${plugin} --packageVersion="invalid"`
);
runCLI(
`generate @nx/plugin:migration ${missingMigrationVersion} --project=${plugin} --packageVersion="0.1.0"`
);
runCLI(
`generate @nx/plugin:migration ${goodMigration} --project=${plugin} --packageVersion="0.1.0"`
);
updateFile(`libs/${plugin}/generators.json`, (f) => {
const json = JSON.parse(f);
// @proj/plugin:plugin has an invalid implementation path
json.generators[
badFactoryPath
].factory = `./generators/${plugin}/bad-path`;
// @proj/plugin:non-existant has a missing implementation path amd schema
json.generators['non-existant-generator'] = {};
return JSON.stringify(json);
});
updateFile(`libs/${plugin}/executors.json`, (f) => {
const json = JSON.parse(f);
// @proj/plugin:badExecutorBadImplPath has an invalid implementation path
json.executors[badExecutorBadImplPath].implementation =
'./executors/bad-path';
// @proj/plugin:non-existant has a missing implementation path amd schema
json.executors['non-existant-executor'] = {};
return JSON.stringify(json);
});
updateFile(`libs/${plugin}/migrations.json`, (f) => {
const json = JSON.parse(f);
delete json.generators[missingMigrationVersion].version;
return JSON.stringify(json);
});
const results = runCLI(`lint ${plugin}`, { silenceError: true });
expect(results).toContain(
`${badFactoryPath}: Implementation path should point to a valid file`
);
expect(results).toContain(
`non-existant-generator: Missing required property - \`schema\``
);
expect(results).toContain(
`non-existant-generator: Missing required property - \`implementation\``
);
expect(results).not.toContain(goodGenerator);
expect(results).toContain(
`${badExecutorBadImplPath}: Implementation path should point to a valid file`
);
expect(results).toContain(
`non-existant-executor: Missing required property - \`schema\``
);
expect(results).toContain(
`non-existant-executor: Missing required property - \`implementation\``
);
expect(results).not.toContain(goodExecutor);
expect(results).toContain(
`${missingMigrationVersion}: Missing required property - \`version\``
);
expect(results).toContain(
`${badMigrationVersion}: Version should be a valid semver`
);
expect(results).not.toContain(goodMigration);
});
describe('local plugins', () => {
let plugin: string;
beforeEach(() => {
plugin = uniq('plugin');
runCLI(`generate @nx/plugin:plugin ${plugin} --linter=eslint`);
});
it('should be able to infer projects and targets (v1)', async () => {
// Setup project inference + target inference
updateFile(
`libs/${plugin}/src/index.ts`,
`import {basename} from 'path'
export function registerProjectTargets(f) {
if (basename(f) === 'my-project-file') {
return {
build: {
executor: "nx:run-commands",
options: {
command: "echo 'custom registered target'"
}
}
}
}
}
export const projectFilePatterns = ['my-project-file'];
`
);
// Register plugin in nx.json (required for inference)
updateFile(`nx.json`, (nxJson) => {
const nx = JSON.parse(nxJson);
nx.plugins = [`@${workspaceName}/${plugin}`];
return JSON.stringify(nx, null, 2);
});
// Create project that should be inferred by Nx
const inferredProject = uniq('inferred');
createFile(`libs/${inferredProject}/my-project-file`);
// Attempt to use inferred project w/ Nx
expect(runCLI(`build ${inferredProject}`)).toContain(
'custom registered target'
);
});
it('should be able to infer projects and targets (v2)', async () => {
// Setup project inference + target inference
updateFile(`libs/${plugin}/src/index.ts`, NX_PLUGIN_V2_CONTENTS);
// Register plugin in nx.json (required for inference)
updateFile(`nx.json`, (nxJson) => {
const nx = JSON.parse(nxJson);
nx.plugins = [
{
plugin: `@${workspaceName}/${plugin}`,
options: { inferredTags: ['my-tag'] },
},
];
return JSON.stringify(nx, null, 2);
});
// Create project that should be inferred by Nx
const inferredProject = uniq('inferred');
createFile(`libs/${inferredProject}/my-project-file`);
// Attempt to use inferred project w/ Nx
expect(runCLI(`build ${inferredProject}`)).toContain(
'custom registered target'
);
const configuration = JSON.parse(
runCLI(`show project ${inferredProject} --json`)
);
expect(configuration.tags).toEqual(['my-tag']);
});
it('should be able to use local generators and executors', async () => {
const generator = uniq('generator');
const executor = uniq('executor');
const generatedProject = uniq('project');
runCLI(`generate @nx/plugin:generator ${generator} --project=${plugin}`);
runCLI(`generate @nx/plugin:executor ${executor} --project=${plugin}`);
updateFile(
`libs/${plugin}/src/executors/${executor}/executor.ts`,
ASYNC_GENERATOR_EXECUTOR_CONTENTS
);
runCLI(
`generate @${workspaceName}/${plugin}:${generator} --name ${generatedProject}`
);
updateFile(`libs/${generatedProject}/project.json`, (f) => {
const project: ProjectConfiguration = JSON.parse(f);
project.targets['execute'] = {
executor: `@${workspaceName}/${plugin}:${executor}`,
};
return JSON.stringify(project, null, 2);
});
expect(() => checkFilesExist(`libs/${generatedProject}`)).not.toThrow();
expect(() => runCLI(`execute ${generatedProject}`)).not.toThrow();
});
it('should work with ts-node only', async () => {
const oldPackageJson: PackageJson = readJson('package.json');
updateJson<PackageJson>('package.json', (j) => {
delete j.dependencies['@swc-node/register'];
delete j.devDependencies['@swc-node/register'];
return j;
});
runCommand(getPackageManagerCommand().install);
const generator = uniq('generator');
expect(() => {
runCLI(
`generate @nx/plugin:generator ${generator} --project=${plugin}`
);
runCLI(
`generate @${workspaceName}/${plugin}:${generator} --name ${uniq(
'test'
)}`
);
}).not.toThrow();
updateFile('package.json', JSON.stringify(oldPackageJson, null, 2));
runCommand(getPackageManagerCommand().install);
});
});
describe('--directory', () => {
it('should create a plugin in the specified directory', async () => {
const plugin = uniq('plugin');
runCLI(
`generate @nx/plugin:plugin ${plugin} --linter=eslint --directory subdir --e2eTestRunner=jest`
);
checkFilesExist(`libs/subdir/${plugin}/package.json`);
const pluginProject = readJson(
join('libs', 'subdir', plugin, 'project.json')
);
const pluginE2EProject = readJson(
join('apps', 'subdir', `${plugin}-e2e`, 'project.json')
);
expect(pluginProject.targets).toBeDefined();
expect(pluginE2EProject).toBeTruthy();
}, 90000);
});
describe('--tags', () => {
it('should add tags to project configuration', () => {
const plugin = uniq('plugin');
runCLI(
`generate @nx/plugin:plugin ${plugin} --linter=eslint --tags=e2etag,e2ePackage `
);
const pluginProject = readJson(join('libs', plugin, 'project.json'));
expect(pluginProject.tags).toEqual(['e2etag', 'e2ePackage']);
}, 90000);
});
it('should be able to generate a create-package plugin ', async () => {
const plugin = uniq('plugin');
const createAppName = `create-${plugin}-app`;
runCLI(
`generate @nx/plugin:plugin ${plugin} --e2eTestRunner jest --publishable`
);
runCLI(
`generate @nx/plugin:create-package ${createAppName} --project=${plugin} --e2eProject=${plugin}-e2e`
);
const buildResults = runCLI(`build ${createAppName}`);
expect(buildResults).toContain('Done compiling TypeScript files');
checkFilesExist(
`libs/${plugin}/src/generators/preset`,
`libs/${createAppName}`,
`dist/libs/${createAppName}/bin/index.js`
);
runCLI(`e2e ${plugin}-e2e`);
});
it('should throw an error when run create-package for an invalid plugin ', async () => {
const plugin = uniq('plugin');
expect(() =>
runCLI(
`generate @nx/plugin:create-package ${plugin} --project=invalid-plugin`
)
).toThrow();
});
it('should support the new name and root format', async () => {
const plugin = uniq('plugin');
const createAppName = `create-${plugin}-app`;
runCLI(
`generate @nx/plugin:plugin ${plugin} --e2eTestRunner jest --publishable --project-name-and-root-format=as-provided`
);
// check files are generated without the layout directory ("libs/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${plugin}/src/index.ts`);
// check build works
expect(runCLI(`build ${plugin}`)).toContain(
`Successfully ran target build for project ${plugin}`
);
// check tests pass
const appTestResult = runCLI(`test ${plugin}`);
expect(appTestResult).toContain(
`Successfully ran target test for project ${plugin}`
);
runCLI(
`generate @nx/plugin:create-package ${createAppName} --project=${plugin} --e2eProject=${plugin}-e2e --project-name-and-root-format=as-provided`
);
// check files are generated without the layout directory ("libs/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${plugin}/src/generators/preset`, `${createAppName}`);
// check build works
expect(runCLI(`build ${createAppName}`)).toContain(
`Successfully ran target build for project ${createAppName}`
);
// check tests pass
const libTestResult = runCLI(`test ${createAppName}`);
expect(libTestResult).toContain(
`Successfully ran target test for project ${createAppName}`
);
});
});
|
2,020 | 0 | petrpan-code/nrwl/nx/e2e/react-core | petrpan-code/nrwl/nx/e2e/react-core/src/react-module-federation.test.ts | import { Tree, stripIndents } from '@nx/devkit';
import {
checkFilesExist,
cleanupProject,
fileExists,
killPorts,
killProcessAndPorts,
newProject,
readJson,
runCLI,
runCLIAsync,
runCommandUntil,
runE2ETests,
tmpProjPath,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { join } from 'path';
import { createTreeWithEmptyWorkspace } from 'nx/src/devkit-testing-exports';
describe('React Module Federation', () => {
let proj: string;
let tree: Tree;
beforeAll(() => {
tree = createTreeWithEmptyWorkspace();
proj = newProject();
});
afterAll(() => cleanupProject());
it('should generate host and remote apps', async () => {
const shell = uniq('shell');
const remote1 = uniq('remote1');
const remote2 = uniq('remote2');
const remote3 = uniq('remote3');
runCLI(`generate @nx/react:host ${shell} --style=css --no-interactive`);
runCLI(
`generate @nx/react:remote ${remote1} --style=css --host=${shell} --no-interactive`
);
runCLI(
`generate @nx/react:remote ${remote2} --style=css --host=${shell} --no-interactive`
);
runCLI(
`generate @nx/react:remote ${remote3} --style=css --host=${shell} --no-interactive`
);
checkFilesExist(`apps/${shell}/module-federation.config.ts`);
checkFilesExist(`apps/${remote1}/module-federation.config.ts`);
checkFilesExist(`apps/${remote2}/module-federation.config.ts`);
checkFilesExist(`apps/${remote3}/module-federation.config.ts`);
await expect(runCLIAsync(`test ${shell}`)).resolves.toMatchObject({
combinedOutput: expect.stringContaining('Test Suites: 1 passed, 1 total'),
});
expect(readPort(shell)).toEqual(4200);
expect(readPort(remote1)).toEqual(4201);
expect(readPort(remote2)).toEqual(4202);
expect(readPort(remote3)).toEqual(4203);
updateFile(
`apps/${shell}/webpack.config.ts`,
stripIndents`
import { composePlugins, withNx, ModuleFederationConfig } from '@nx/webpack';
import { withReact } from '@nx/react';
import { withModuleFederation } from '@nx/react/module-federation';
import baseConfig from './module-federation.config';
const config: ModuleFederationConfig = {
...baseConfig,
remotes: [
'${remote1}',
['${remote2}', 'http://localhost:${readPort(
remote2
)}/remoteEntry.js'],
['${remote3}', 'http://localhost:${readPort(remote3)}'],
],
};
// Nx plugins for webpack to build config object from Nx options and context.
module.exports = composePlugins(withNx(), withReact(), withModuleFederation(config));
`
);
updateFile(
`apps/${shell}-e2e/src/integration/app.spec.ts`,
stripIndents`
import { getGreeting } from '../support/app.po';
describe('shell app', () => {
it('should display welcome message', () => {
cy.visit('/')
getGreeting().contains('Welcome ${shell}');
});
it('should load remote 1', () => {
cy.visit('/${remote1}')
getGreeting().contains('Welcome ${remote1}');
});
it('should load remote 2', () => {
cy.visit('/${remote2}')
getGreeting().contains('Welcome ${remote2}');
});
it('should load remote 3', () => {
cy.visit('/${remote3}')
getGreeting().contains('Welcome ${remote3}');
});
});
`
);
if (runE2ETests()) {
const e2eResultsSwc = await runCommandUntil(
`e2e ${shell}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);
await killProcessAndPorts(
e2eResultsSwc.pid,
readPort(shell),
readPort(remote1),
readPort(remote2),
readPort(remote3)
);
const e2eResultsTsNode = await runCommandUntil(
`e2e ${shell}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!'),
{
env: { NX_PREFER_TS_NODE: 'true' },
}
);
await killProcessAndPorts(
e2eResultsTsNode.pid,
readPort(shell),
readPort(remote1),
readPort(remote2),
readPort(remote3)
);
}
}, 500_000);
it('should generate host and remote apps with ssr', async () => {
const shell = uniq('shell');
const remote1 = uniq('remote1');
const remote2 = uniq('remote2');
const remote3 = uniq('remote3');
await runCLIAsync(
`generate @nx/react:host ${shell} --ssr --remotes=${remote1},${remote2},${remote3} --style=css --no-interactive --projectNameAndRootFormat=derived`
);
expect(readPort(shell)).toEqual(4200);
expect(readPort(remote1)).toEqual(4201);
expect(readPort(remote2)).toEqual(4202);
expect(readPort(remote3)).toEqual(4203);
[shell, remote1, remote2, remote3].forEach((app) => {
checkFilesExist(
`apps/${app}/module-federation.config.ts`,
`apps/${app}/module-federation.server.config.ts`
);
['build', 'server'].forEach((target) => {
['development', 'production'].forEach(async (configuration) => {
const cliOutput = runCLI(`run ${app}:${target}:${configuration}`);
expect(cliOutput).toContain('Successfully ran target');
await killPorts(readPort(app));
});
});
});
}, 500_000);
it('should should support generating host and remote apps with the new name and root format', async () => {
const shell = uniq('shell');
const remote = uniq('remote');
runCLI(
`generate @nx/react:host ${shell} --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/react:remote ${remote} --host=${shell} --project-name-and-root-format=as-provided --no-interactive`
);
const shellPort = readPort(shell);
const remotePort = readPort(remote);
// check files are generated without the layout directory ("apps/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${shell}/module-federation.config.ts`);
checkFilesExist(`${remote}/module-federation.config.ts`);
// check default generated host is built successfully
const buildOutputSwc = runCLI(`run ${shell}:build:development`);
expect(buildOutputSwc).toContain('Successfully ran target build');
const buildOutputTsNode = runCLI(`run ${shell}:build:development`, {
env: { NX_PREFER_TS_NODE: 'true' },
});
expect(buildOutputTsNode).toContain('Successfully ran target build');
// check serves devRemotes ok
const shellProcessSwc = await runCommandUntil(
`serve ${shell} --devRemotes=${remote} --verbose`,
(output) => {
return output.includes(
`All remotes started, server ready at http://localhost:${shellPort}`
);
}
);
await killProcessAndPorts(
shellProcessSwc.pid,
shellPort,
remotePort + 1,
remotePort
);
const shellProcessTsNode = await runCommandUntil(
`serve ${shell} --devRemotes=${remote} --verbose`,
(output) => {
return output.includes(
`All remotes started, server ready at http://localhost:${shellPort}`
);
},
{
env: { NX_PREFER_TS_NODE: 'true' },
}
);
await killProcessAndPorts(
shellProcessTsNode.pid,
shellPort,
remotePort + 1,
remotePort
);
}, 500_000);
// Federate Module
describe('Federate Module', () => {
let proj: string;
let tree: Tree;
beforeAll(() => {
tree = createTreeWithEmptyWorkspace();
proj = newProject();
});
afterAll(() => cleanupProject());
it('should federate a module from a library and update an existing remote', async () => {
const lib = uniq('lib');
const remote = uniq('remote');
const module = uniq('module');
const host = uniq('host');
runCLI(
`generate @nx/react:host ${host} --remotes=${remote} --no-interactive --projectNameAndRootFormat=as-provided`
);
runCLI(
`generate @nx/js:lib ${lib} --no-interactive --projectNameAndRootFormat=as-provided`
);
// Federate Module
runCLI(
`generate @nx/react:federate-module ${lib}/src/index.ts --name=${module} --remote=${remote} --no-interactive`
);
updateFile(
`${lib}/src/index.ts`,
`export { default } from './lib/${lib}';`
);
updateFile(
`${lib}/src/lib/${lib}.ts`,
`export default function lib() { return 'Hello from ${lib}'; };`
);
// Update Host to use the module
updateFile(
`${host}/src/app/app.tsx`,
`
import * as React from 'react';
import NxWelcome from './nx-welcome';
import { Link, Route, Routes } from 'react-router-dom';
import myLib from '${remote}/${module}';
export function App() {
return (
<React.Suspense fallback={null}>
<div className='remote'>
My Remote Library: { myLib() }
</div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
</ul>
<Routes>
<Route path="/" element={<NxWelcome title="Host" />} />
</Routes>
</React.Suspense>
);
}
export default App;
`
);
// Update e2e test to check the module
updateFile(
`${host}-e2e/src/e2e/app.cy.ts`,
`
describe('${host}', () => {
beforeEach(() => cy.visit('/'));
it('should display contain the remote library', () => {
expect(cy.get('div.remote')).to.exist;
expect(cy.get('div.remote').contains('My Remote Library: Hello from ${lib}'));
});
});
`
);
const hostPort = readPort(host);
const remotePort = readPort(remote);
// Build host and remote
const buildOutput = runCLI(`build ${host}`);
const remoteOutput = runCLI(`build ${remote}`);
expect(buildOutput).toContain('Successfully ran target build');
expect(remoteOutput).toContain('Successfully ran target build');
if (runE2ETests()) {
const hostE2eResults = await runCommandUntil(
`e2e ${host}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);
await killProcessAndPorts(
hostE2eResults.pid,
hostPort,
hostPort + 1,
remotePort
);
}
}, 500_000);
it('should federate a module from a library and create a remote and serve it recursively', async () => {
const lib = uniq('lib');
const remote = uniq('remote');
const childRemote = uniq('childremote');
const module = uniq('module');
const host = uniq('host');
runCLI(
`generate @nx/react:host ${host} --remotes=${remote} --no-interactive --projectNameAndRootFormat=as-provided`
);
runCLI(
`generate @nx/js:lib ${lib} --no-interactive --projectNameAndRootFormat=as-provided`
);
// Federate Module
runCLI(
`generate @nx/react:federate-module ${lib}/src/index.ts --name=${module} --remote=${childRemote} --no-interactive`
);
updateFile(
`${lib}/src/index.ts`,
`export { default } from './lib/${lib}';`
);
updateFile(
`${lib}/src/lib/${lib}.ts`,
`export default function lib() { return 'Hello from ${lib}'; };`
);
// Update Host to use the module
updateFile(
`${remote}/src/app/app.tsx`,
`
import * as React from 'react';
import NxWelcome from './nx-welcome';
import myLib from '${childRemote}/${module}';
export function App() {
return (
<React.Suspense fallback={null}>
<div className='remote'>
My Remote Library: { myLib() }
</div>
<NxWelcome title="Host" />
</React.Suspense>
);
}
export default App;
`
);
// Update e2e test to check the module
updateFile(
`${host}-e2e/src/e2e/app.cy.ts`,
`
describe('${host}', () => {
beforeEach(() => cy.visit('/${remote}'));
it('should display contain the remote library', () => {
expect(cy.get('div.remote')).to.exist;
expect(cy.get('div.remote').contains('My Remote Library: Hello from ${lib}'));
});
});
`
);
const hostPort = readPort(host);
const remotePort = readPort(remote);
const childRemotePort = readPort(childRemote);
// Build host and remote
const buildOutput = runCLI(`build ${host}`);
const remoteOutput = runCLI(`build ${remote}`);
expect(buildOutput).toContain('Successfully ran target build');
expect(remoteOutput).toContain('Successfully ran target build');
if (runE2ETests()) {
const hostE2eResults = await runCommandUntil(
`e2e ${host}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);
await killProcessAndPorts(
hostE2eResults.pid,
hostPort,
hostPort + 1,
remotePort,
childRemotePort
);
}
}, 500_000);
});
describe('Independent Deployability', () => {
let proj: string;
let tree: Tree;
beforeAll(() => {
tree = createTreeWithEmptyWorkspace();
proj = newProject();
});
afterAll(() => cleanupProject());
it('should support promised based remotes', async () => {
const remote = uniq('remote');
const host = uniq('host');
runCLI(
`generate @nx/react:host ${host} --remotes=${remote} --no-interactive --projectNameAndRootFormat=as-provided --typescriptConfiguration=false`
);
// Update remote to be loaded via script
updateFile(
`${remote}/module-federation.config.js`,
stripIndents`
module.exports = {
name: '${remote}',
library: { type: 'var', name: '${remote}' },
exposes: {
'./Module': './src/remote-entry.ts',
},
};
`
);
updateFile(
`${remote}/webpack.config.prod.js`,
`module.exports = require('./webpack.config');`
);
// Update host to use promise based remote
updateFile(
`${host}/module-federation.config.js`,
`module.exports = {
name: '${host}',
library: { type: 'var', name: '${host}' },
remotes: [
[
'${remote}',
\`promise new Promise(resolve => {
const remoteUrl = 'http://localhost:4201/remoteEntry.js';
const script = document.createElement('script');
script.src = remoteUrl;
script.onload = () => {
const proxy = {
get: (request) => window.${remote}.get(request),
init: (arg) => {
try {
window.${remote}.init(arg);
} catch (e) {
console.log('Remote container already initialized');
}
}
};
resolve(proxy);
}
document.head.appendChild(script);
})\`,
],
],
};
`
);
updateFile(
`${host}/webpack.config.prod.js`,
`module.exports = require('./webpack.config');`
);
// Update e2e project.json
updateJson(`${host}-e2e/project.json`, (json) => {
return {
...json,
targets: {
...json.targets,
e2e: {
...json.targets.e2e,
options: {
...json.targets.e2e.options,
devServerTarget: `${host}:serve-static:production`,
},
},
},
};
});
// update e2e
updateFile(
`${host}-e2e/src/e2e/app.cy.ts`,
`
import { getGreeting } from '../support/app.po';
describe('${host}', () => {
beforeEach(() => cy.visit('/'));
it('should display welcome message', () => {
getGreeting().contains('Welcome ${host}');
});
it('should navigate to /${remote} from /', () => {
cy.get('a').contains('${remote[0].toUpperCase()}${remote.slice(
1
)}').click();
cy.url().should('include', '/${remote}');
getGreeting().contains('Welcome ${remote}');
});
});
`
);
const hostPort = readPort(host);
const remotePort = readPort(remote);
// Build host and remote
const buildOutput = runCLI(`build ${host}`);
const remoteOutput = runCLI(`build ${remote}`);
expect(buildOutput).toContain('Successfully ran target build');
expect(remoteOutput).toContain('Successfully ran target build');
if (runE2ETests()) {
const remoteProcess = await runCommandUntil(
`serve-static ${remote} --no-watch --verbose`,
() => {
return true;
}
);
const hostE2eResults = await runCommandUntil(
`e2e ${host}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);
await killProcessAndPorts(hostE2eResults.pid, hostPort, hostPort + 1);
await killProcessAndPorts(remoteProcess.pid, remotePort);
}
}, 500_000);
it('should support different versions workspace libs for host and remote', async () => {
const shell = uniq('shell');
const remote = uniq('remote');
const lib = uniq('lib');
runCLI(
`generate @nx/react:host ${shell} --remotes=${remote} --no-interactive --projectNameAndRootFormat=as-provided`
);
runCLI(
`generate @nx/js:lib ${lib} --importPath=@acme/${lib} --publishable=true --no-interactive --projectNameAndRootFormat=as-provided`
);
const shellPort = readPort(shell);
const remotePort = readPort(remote);
updateFile(
`${lib}/src/lib/${lib}.ts`,
stripIndents`
export const version = '0.0.1';
`
);
updateJson(`${lib}/package.json`, (json) => {
return {
...json,
version: '0.0.1',
};
});
// Update host to use the lib
updateFile(
`${shell}/src/app/app.tsx`,
`
import * as React from 'react';
import NxWelcome from './nx-welcome';
import { version } from '@acme/${lib}';
import { Link, Route, Routes } from 'react-router-dom';
const About = React.lazy(() => import('${remote}/Module'));
export function App() {
return (
<React.Suspense fallback={null}>
<div className="home">
Lib version: { version }
</div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/About">About</Link>
</li>
</ul>
<Routes>
<Route path="/" element={<NxWelcome title="home" />} />
<Route path="/About" element={<About />} />
</Routes>
</React.Suspense>
);
}
export default App;`
);
// Update remote to use the lib
updateFile(
`${remote}/src/app/app.tsx`,
`// eslint-disable-next-line @typescript-eslint/no-unused-vars
import styles from './app.module.css';
import { version } from '@acme/${lib}';
import NxWelcome from './nx-welcome';
export function App() {
return (
<div className='remote'>
Lib version: { version }
<NxWelcome title="${remote}" />
</div>
);
}
export default App;`
);
// update remote e2e test to check the version
updateFile(
`${remote}-e2e/src/e2e/app.cy.ts`,
`describe('${remote}', () => {
beforeEach(() => cy.visit('/'));
it('should check the lib version', () => {
cy.get('div.remote').contains('Lib version: 0.0.1');
});
});
`
);
// update shell e2e test to check the version
updateFile(
`${shell}-e2e/src/e2e/app.cy.ts`,
`
describe('${shell}', () => {
beforeEach(() => cy.visit('/'));
it('should check the lib version', () => {
cy.get('div.home').contains('Lib version: 0.0.1');
});
});
`
);
if (runE2ETests()) {
// test remote e2e
const remoteE2eResults = await runCommandUntil(
`e2e ${remote}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);
await killProcessAndPorts(remoteE2eResults.pid, remotePort);
// test shell e2e
// serve remote first
const remoteProcess = await runCommandUntil(
`serve ${remote} --no-watch --verbose`,
(output) => {
return output.includes(
`Web Development Server is listening at http://localhost:${remotePort}/`
);
}
);
await killProcessAndPorts(remoteProcess.pid, remotePort);
const shellE2eResults = await runCommandUntil(
`e2e ${shell}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);
await killProcessAndPorts(
shellE2eResults.pid,
shellPort,
shellPort + 1,
remotePort
);
}
}, 500_000);
it('should support host and remote with library type var', async () => {
const shell = uniq('shell');
const remote = uniq('remote');
runCLI(
`generate @nx/react:host ${shell} --remotes=${remote} --project-name-and-root-format=as-provided --no-interactive`
);
const shellPort = readPort(shell);
const remotePort = readPort(remote);
// update host and remote to use library type var
updateFile(
`${shell}/module-federation.config.ts`,
stripIndents`
import { ModuleFederationConfig } from '@nx/webpack';
const config: ModuleFederationConfig = {
name: '${shell}',
library: { type: 'var', name: '${shell}' },
remotes: ['${remote}'],
};
export default config;
`
);
updateFile(
`${shell}/webpack.config.prod.ts`,
`export { default } from './webpack.config';`
);
updateFile(
`${remote}/module-federation.config.ts`,
stripIndents`
import { ModuleFederationConfig } from '@nx/webpack';
const config: ModuleFederationConfig = {
name: '${remote}',
library: { type: 'var', name: '${remote}' },
exposes: {
'./Module': './src/remote-entry.ts',
},
};
export default config;
`
);
updateFile(
`${remote}/webpack.config.prod.ts`,
`export { default } from './webpack.config';`
);
// Update host e2e test to check that the remote works with library type var via navigation
updateFile(
`${shell}-e2e/src/e2e/app.cy.ts`,
`
import { getGreeting } from '../support/app.po';
describe('${shell}', () => {
beforeEach(() => cy.visit('/'));
it('should display welcome message', () => {
getGreeting().contains('Welcome ${shell}');
});
it('should navigate to /about from /', () => {
cy.get('a').contains('${remote[0].toUpperCase()}${remote.slice(
1
)}').click();
cy.url().should('include', '/${remote}');
getGreeting().contains('Welcome ${remote}');
});
});
`
);
// Build host and remote
const buildOutput = runCLI(`build ${shell}`);
const remoteOutput = runCLI(`build ${remote}`);
expect(buildOutput).toContain('Successfully ran target build');
expect(remoteOutput).toContain('Successfully ran target build');
if (runE2ETests()) {
const hostE2eResultsSwc = await runCommandUntil(
`e2e ${shell}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);
await killProcessAndPorts(
hostE2eResultsSwc.pid,
shellPort,
shellPort + 1,
remotePort
);
const remoteE2eResultsSwc = await runCommandUntil(
`e2e ${remote}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);
await killProcessAndPorts(remoteE2eResultsSwc.pid, remotePort);
const hostE2eResultsTsNode = await runCommandUntil(
`e2e ${shell}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!'),
{ env: { NX_PREFER_TS_NODE: 'true' } }
);
await killProcessAndPorts(
hostE2eResultsTsNode.pid,
shellPort,
shellPort + 1,
remotePort
);
const remoteE2eResultsTsNode = await runCommandUntil(
`e2e ${remote}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!'),
{ env: { NX_PREFER_TS_NODE: 'true' } }
);
await killProcessAndPorts(remoteE2eResultsTsNode.pid, remotePort);
}
}, 500_000);
});
describe('Dynamic Module Federation', () => {
beforeAll(() => {
tree = createTreeWithEmptyWorkspace();
proj = newProject();
});
afterAll(() => cleanupProject());
it('should load remote dynamic module', async () => {
const shell = uniq('shell');
const remote = uniq('remote');
runCLI(
`generate @nx/react:host ${shell} --remotes=${remote} --dynamic=true --project-name-and-root-format=as-provided --no-interactive`
);
// Webpack prod config should not exists when loading dynamic modules
expect(
fileExists(`${tmpProjPath()}/${shell}/webpack.config.prod.ts`)
).toBeFalsy();
expect(
fileExists(
`${tmpProjPath()}/${shell}/src/assets/module-federation.manifest.json`
)
).toBeTruthy();
const manifest = readJson(
`${shell}/src/assets/module-federation.manifest.json`
);
expect(manifest[remote]).toBeDefined();
expect(manifest[remote]).toEqual('http://localhost:4201');
// update e2e
updateFile(
`${shell}-e2e/src/e2e/app.cy.ts`,
`
import { getGreeting } from '../support/app.po';
describe('${shell}', () => {
beforeEach(() => cy.visit('/'));
it('should display welcome message', () => {
getGreeting().contains('Welcome ${shell}');
});
it('should navigate to /${remote} from /', () => {
cy.get('a').contains('${remote[0].toUpperCase()}${remote.slice(
1
)}').click();
cy.url().should('include', '/${remote}');
getGreeting().contains('Welcome ${remote}');
});
});
`
);
// Build host and remote
const buildOutput = runCLI(`build ${shell}`);
const remoteOutput = runCLI(`build ${remote}`);
expect(buildOutput).toContain('Successfully ran target build');
expect(remoteOutput).toContain('Successfully ran target build');
const shellPort = readPort(shell);
const remotePort = readPort(remote);
if (runE2ETests()) {
// Serve Remote since it is dynamic and won't be started with the host
const remoteProcess = await runCommandUntil(
`serve-static ${remote} --no-watch --verbose`,
() => {
return true;
}
);
const hostE2eResultsSwc = await runCommandUntil(
`e2e ${shell}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);
await killProcessAndPorts(remoteProcess.pid, remotePort);
await killProcessAndPorts(hostE2eResultsSwc.pid, shellPort);
}
}, 500_000);
});
});
function readPort(appName: string): number {
let config;
try {
config = readJson(join('apps', appName, 'project.json'));
} catch {
config = readJson(join(appName, 'project.json'));
}
return config.targets.serve.options.port;
}
|
2,021 | 0 | petrpan-code/nrwl/nx/e2e/react-core | petrpan-code/nrwl/nx/e2e/react-core/src/react-package.test.ts | import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
getSize,
killPorts,
newProject,
readFile,
readJson,
rmDist,
runCLI,
runCLIAsync,
tmpProjPath,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { names } from '@nx/devkit';
import { join } from 'path';
describe('Build React libraries and apps', () => {
/**
* Graph:
*
* childLib
* /
* app => parentLib =>
* \
* childLib2
*
*/
let app: string;
let parentLib: string;
let childLib: string;
let childLib2: string;
let proj: string;
beforeEach(async () => {
app = uniq('app');
parentLib = uniq('parentlib');
childLib = uniq('childlib');
childLib2 = uniq('childlib2');
proj = newProject();
// create dependencies by importing
const createDep = (parent, children: string[]) => {
updateFile(
`libs/${parent}/src/index.ts`,
`
export * from './lib/${parent}';
${children
.map(
(entry) =>
`import { ${
names(entry).className
} } from '@${proj}/${entry}'; console.log(${
names(entry).className
});`
)
.join('\n')}
`
);
};
runCLI(`generate @nx/react:app ${app} `);
updateJson('nx.json', (json) => ({
...json,
generators: {
...json.generators,
'@nx/react': {
library: {
unitTestRunner: 'none',
},
},
},
}));
// generate buildable libs
runCLI(
`generate @nx/react:library ${parentLib} --bundler=rollup --importPath=@${proj}/${parentLib} --no-interactive --unitTestRunner=jest`
);
runCLI(
`generate @nx/react:library ${childLib} --bundler=rollup --importPath=@${proj}/${childLib} --no-interactive --unitTestRunner=jest`
);
runCLI(
`generate @nx/react:library ${childLib2} --bundler=rollup --importPath=@${proj}/${childLib2} --no-interactive --unitTestRunner=jest`
);
createDep(parentLib, [childLib, childLib2]);
updateFile(
`apps/${app}/src/main.tsx`,
`
import {${names(parentLib).className}} from "@${proj}/${parentLib}";
console.log(${names(parentLib).className});
`
);
// Add assets to child lib
updateJson(join('libs', childLib, 'project.json'), (json) => {
json.targets.build.options.assets = [`libs/${childLib}/src/assets`];
return json;
});
updateFile(`libs/${childLib}/src/assets/hello.txt`, 'Hello World!');
});
afterEach(() => {
killPorts();
cleanupProject();
});
describe('Buildable libraries', () => {
it('should build libraries with and without dependencies', () => {
/*
* 1. Without dependencies
*/
runCLI(`build ${childLib}`);
runCLI(`build ${childLib2}`);
checkFilesExist(`dist/libs/${childLib}/index.esm.js`);
checkFilesExist(`dist/libs/${childLib2}/index.esm.js`);
checkFilesExist(`dist/libs/${childLib}/assets/hello.txt`);
checkFilesExist(`dist/libs/${childLib2}/README.md`);
/*
* 2. With dependencies without existing dist
*/
rmDist();
runCLI(`build ${parentLib} --skip-nx-cache`);
checkFilesExist(`dist/libs/${parentLib}/index.esm.js`);
checkFilesExist(`dist/libs/${childLib}/index.esm.js`);
checkFilesExist(`dist/libs/${childLib2}/index.esm.js`);
expect(readFile(`dist/libs/${childLib}/index.esm.js`)).not.toContain(
'react/jsx-dev-runtime'
);
expect(readFile(`dist/libs/${childLib}/index.esm.js`)).toContain(
'react/jsx-runtime'
);
});
it('should support --format option', () => {
updateFile(
`libs/${childLib}/src/index.ts`,
(s) => `${s}
export async function f() { return 'a'; }
export async function g() { return 'b'; }
export async function h() { return 'c'; }
`
);
runCLI(`build ${childLib} --format cjs,esm`);
checkFilesExist(`dist/libs/${childLib}/index.cjs.js`);
checkFilesExist(`dist/libs/${childLib}/index.esm.js`);
const cjsPackageSize = getSize(
tmpProjPath(`dist/libs/${childLib}/index.cjs.js`)
);
const esmPackageSize = getSize(
tmpProjPath(`dist/libs/${childLib}/index.esm.js`)
);
// This is a loose requirement that ESM should be smaller than CJS output.
expect(esmPackageSize).toBeLessThanOrEqual(cjsPackageSize);
});
it('should preserve the tsconfig target set by user', () => {
// Setup
const myLib = uniq('my-lib');
runCLI(
`generate @nx/react:library ${myLib} --bundler=rollup --publishable --importPath="@mproj/${myLib}" --no-interactive --unitTestRunner=jest`
);
/**
*
* Here I update my library file
* I am just adding this in the end:
*
* export const TestFunction = async () => {
* return await Promise.resolve('Done!')
* }
*
* So that I can see the change in the Promise.
*
*/
updateFile(`libs/${myLib}/src/lib/${myLib}.tsx`, (content) => {
return `
${content} \n
export const TestFunction = async () => {
return await Promise.resolve('Done!')
}
`;
});
updateFile(`libs/${myLib}/tsconfig.json`, (content) => {
const json = JSON.parse(content);
/**
* Set target as es5!!
*/
json.compilerOptions.target = 'es5';
return JSON.stringify(json, null, 2);
});
// What we're testing
runCLI(`build ${myLib}`);
// Assertion
const content = readFile(`dist/libs/${myLib}/index.esm.js`);
/**
* Then check if the result contains this "promise" polyfill?
*/
expect(content).toContain('function __generator(thisArg, body) {');
});
it('should build an app composed out of buildable libs', () => {
const buildFromSource = runCLI(
`build ${app} --buildLibsFromSource=false`
);
expect(buildFromSource).toContain('Successfully ran target build');
checkFilesDoNotExist(`apps/${app}/tsconfig/tsconfig.nx-tmp`);
}, 1000000);
it('should not create a dist folder if there is an error', async () => {
const libName = uniq('lib');
runCLI(
`generate @nx/react:lib ${libName} --bundler=rollup --importPath=@${proj}/${libName} --no-interactive --unitTestRunner=jest`
);
const mainPath = `libs/${libName}/src/lib/${libName}.tsx`;
updateFile(mainPath, `${readFile(mainPath)}\n console.log(a);`); // should error - "a" will be undefined
await expect(runCLIAsync(`build ${libName}`)).rejects.toThrow(
/Bundle failed/
);
expect(() => {
checkFilesExist(`dist/libs/${libName}/package.json`);
}).toThrow();
}, 250000);
});
});
|
2,022 | 0 | petrpan-code/nrwl/nx/e2e/react-core | petrpan-code/nrwl/nx/e2e/react-core/src/react.test.ts | import {
checkFilesDoNotExist,
checkFilesExist,
cleanupProject,
createFile,
ensureCypressInstallation,
killPorts,
newProject,
readFile,
runCLI,
runCLIAsync,
runE2ETests,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { readFileSync } from 'fs-extra';
import { join } from 'path';
describe('React Applications', () => {
let proj: string;
beforeAll(() => {
proj = newProject();
ensureCypressInstallation();
});
afterAll(() => cleanupProject());
it('should be able to generate a react app + lib (with CSR and SSR)', async () => {
const appName = uniq('app');
const libName = uniq('lib');
const libWithNoComponents = uniq('lib');
const logoSvg = readFileSync(join(__dirname, 'logo.svg')).toString();
runCLI(
`generate @nx/react:app ${appName} --style=css --bundler=webpack --no-interactive`
);
runCLI(
`generate @nx/react:lib ${libName} --style=css --no-interactive --unit-test-runner=jest`
);
runCLI(
`generate @nx/react:lib ${libWithNoComponents} --no-interactive --no-component --unit-test-runner=jest`
);
// Libs should not include package.json by default
checkFilesDoNotExist(`libs/${libName}/package.json`);
const mainPath = `apps/${appName}/src/main.tsx`;
updateFile(
mainPath,
`
import '@${proj}/${libWithNoComponents}';
import '@${proj}/${libName}';
${readFile(mainPath)}
`
);
updateFile(`apps/${appName}/src/app/logo.svg`, logoSvg);
updateFile(
`apps/${appName}/src/app/app.tsx`,
`
import { ReactComponent as Logo } from './logo.svg';
import logo from './logo.svg';
import NxWelcome from './nx-welcome';
export function App() {
return (
<>
<Logo />
<img src={logo} alt="" />
<NxWelcome title="${appName}" />
</>
);
}
export default App;
`
);
// Make sure global stylesheets are properly processed.
const stylesPath = `apps/${appName}/src/styles.css`;
updateFile(
stylesPath,
`
.foobar {
background-image: url('/bg.png');
}
`
);
const libTestResults = await runCLIAsync(`test ${libName}`);
expect(libTestResults.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
await testGeneratedApp(appName, {
checkSourceMap: true,
checkStyles: true,
checkLinter: true,
// TODO(caleb): Fix cypress tests
// /tmp/nx-e2e--1970-rQ4U0qBe6Nht/nx/proj1614306/dist/apps/app5172641/server/runtime.js:119
// if (typeof import.meta.url === "string") scriptUrl = import.meta.url
// SyntaxError: Cannot use 'import.meta' outside a module
checkE2E: false,
});
// Set up SSR and check app
runCLI(`generate @nx/react:setup-ssr ${appName}`);
checkFilesExist(`apps/${appName}/src/main.server.tsx`);
checkFilesExist(`apps/${appName}/server.ts`);
await testGeneratedApp(appName, {
checkSourceMap: false,
checkStyles: false,
checkLinter: false,
// TODO(caleb): Fix cypress tests
// /tmp/nx-e2e--1970-rQ4U0qBe6Nht/nx/proj1614306/dist/apps/app5172641/server/runtime.js:119
// if (typeof import.meta.url === "string") scriptUrl = import.meta.url
// SyntaxError: Cannot use 'import.meta' outside a module
checkE2E: false,
});
}, 500000);
it('should be able to use JS and JSX', async () => {
const appName = uniq('app');
const libName = uniq('lib');
const plainJsLib = uniq('jslib');
runCLI(
`generate @nx/react:app ${appName} --bundler=webpack --no-interactive --js`
);
runCLI(
`generate @nx/react:lib ${libName} --no-interactive --js --unit-test-runner=none`
);
// Make sure plain JS libs can be imported as well.
// There was an issue previously: https://github.com/nrwl/nx/issues/10990
runCLI(
`generate @nx/js:lib ${plainJsLib} --js --unit-test-runner=none --bundler=none --compiler=tsc --no-interactive`
);
const mainPath = `apps/${appName}/src/main.js`;
updateFile(
mainPath,
`import '@${proj}/${libName}';\nimport '@${proj}/${plainJsLib}';\n${readFile(
mainPath
)}`
);
await testGeneratedApp(appName, {
checkStyles: true,
checkLinter: false,
checkE2E: false,
});
}, 250_000);
it('should be able to use Vite to build and test apps', async () => {
const appName = uniq('app');
const libName = uniq('lib');
runCLI(`generate @nx/react:app ${appName} --bundler=vite --no-interactive`);
runCLI(
`generate @nx/react:lib ${libName} --bundler=none --no-interactive --unit-test-runner=vitest`
);
// Library generated with Vite
checkFilesExist(`libs/${libName}/vite.config.ts`);
const mainPath = `apps/${appName}/src/main.tsx`;
updateFile(
mainPath,
`
import '@${proj}/${libName}';
${readFile(mainPath)}
`
);
runCLI(`build ${appName}`);
checkFilesExist(`dist/apps/${appName}/index.html`);
if (runE2ETests()) {
const e2eResults = runCLI(`e2e ${appName}-e2e --no-watch`);
expect(e2eResults).toContain('All specs passed!');
expect(await killPorts()).toBeTruthy();
}
}, 250_000);
it('should generate app with routing', async () => {
const appName = uniq('app');
runCLI(
`generate @nx/react:app ${appName} --routing --bundler=webpack --no-interactive`
);
runCLI(`build ${appName} --outputHashing none`);
checkFilesExist(
`dist/apps/${appName}/index.html`,
`dist/apps/${appName}/runtime.js`,
`dist/apps/${appName}/main.js`
);
}, 250_000);
it('should be able to add a redux slice', async () => {
const appName = uniq('app');
const libName = uniq('lib');
runCLI(`g @nx/react:app ${appName} --bundler=webpack --no-interactive`);
runCLI(`g @nx/react:redux lemon --project=${appName}`);
runCLI(
`g @nx/react:lib ${libName} --unit-test-runner=jest --no-interactive`
);
runCLI(`g @nx/react:redux orange --project=${libName}`);
let lintResults = runCLI(`lint ${appName}`);
expect(lintResults).toContain('All files pass linting.');
const appTestResults = await runCLIAsync(`test ${appName}`);
expect(appTestResults.combinedOutput).toContain(
'Test Suites: 2 passed, 2 total'
);
lintResults = runCLI(`lint ${libName}`);
expect(lintResults).toContain('All files pass linting.');
const libTestResults = await runCLIAsync(`test ${libName}`);
expect(libTestResults.combinedOutput).toContain(
'Test Suites: 2 passed, 2 total'
);
}, 250_000);
it('should support generating projects with the new name and root format', () => {
const appName = uniq('app1');
const libName = uniq('@my-org/lib1');
runCLI(
`generate @nx/react:app ${appName} --bundler=webpack --project-name-and-root-format=as-provided --no-interactive`
);
// check files are generated without the layout directory ("apps/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${appName}/src/main.tsx`);
// check build works
expect(runCLI(`build ${appName}`)).toContain(
`Successfully ran target build for project ${appName}`
);
// check tests pass
const appTestResult = runCLI(`test ${appName}`);
expect(appTestResult).toContain(
`Successfully ran target test for project ${appName}`
);
// assert scoped project names are not supported when --project-name-and-root-format=derived
expect(() =>
runCLI(
`generate @nx/react:lib ${libName} --unit-test-runner=jest --buildable --project-name-and-root-format=derived --no-interactive`
)
).toThrow();
runCLI(
`generate @nx/react:lib ${libName} --unit-test-runner=jest --buildable --project-name-and-root-format=as-provided --no-interactive`
);
// check files are generated without the layout directory ("libs/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${libName}/src/index.ts`);
// check build works
expect(runCLI(`build ${libName}`)).toContain(
`Successfully ran target build for project ${libName}`
);
// check tests pass
const libTestResult = runCLI(`test ${libName}`);
expect(libTestResult).toContain(
`Successfully ran target test for project ${libName}`
);
}, 500_000);
describe('React Applications: --style option', () => {
it('should support styled-jsx', async () => {
const appName = uniq('app');
runCLI(
`generate @nx/react:app ${appName} --style=styled-jsx --bundler=vite --no-interactive`
);
// update app to use styled-jsx
updateFile(
`apps/${appName}/src/app/app.tsx`,
`
import NxWelcome from './nx-welcome';
export function App() {
return (
<div>
<style jsx>{'h1 { color: red }'}</style>
<NxWelcome title="${appName}" />
</div>
);
}
export default App;
`
);
// update e2e test to check for styled-jsx change
updateFile(
`apps/${appName}-e2e/src/e2e/app.cy.ts`,
`
describe('react-test', () => {
beforeEach(() => cy.visit('/'));
it('should have red colour', () => {
cy.get('h1').should('have.css', 'color', 'rgb(255, 0, 0)');
});
});
`
);
if (runE2ETests()) {
const e2eResults = runCLI(`e2e ${appName}-e2e --no-watch --verbose`);
expect(e2eResults).toContain('All specs passed!');
}
}, 250_000);
it.each`
style
${'css'}
${'scss'}
${'less'}
`('should support global and css modules', async ({ style }) => {
const appName = uniq('app');
runCLI(
`generate @nx/react:app ${appName} --style=${style} --bundler=webpack --no-interactive`
);
// make sure stylePreprocessorOptions works
updateJson(join('apps', appName, 'project.json'), (config) => {
config.targets.build.options.stylePreprocessorOptions = {
includePaths: ['libs/shared/lib'],
};
return config;
});
updateFile(
`apps/${appName}/src/styles.${style}`,
`@import 'base.${style}';`
);
updateFile(
`apps/${appName}/src/app/app.module.${style}`,
(s) => `@import 'base.${style}';\n${s}`
);
updateFile(
`libs/shared/lib/base.${style}`,
`body { font-family: "Comic Sans MS"; }`
);
runCLI(`build ${appName} --outputHashing none`);
expect(readFile(`dist/apps/${appName}/styles.css`)).toMatch(
/Comic Sans MS/
);
});
});
describe('React Applications and Libs with PostCSS', () => {
it('should support single path or auto-loading of PostCSS config files', async () => {
const appName = uniq('app');
const libName = uniq('lib');
runCLI(`g @nx/react:app ${appName} --bundler=webpack --no-interactive`);
runCLI(
`g @nx/react:lib ${libName} --no-interactive --unit-test-runner=none`
);
const mainPath = `apps/${appName}/src/main.tsx`;
updateFile(
mainPath,
`import '@${proj}/${libName}';\n${readFile(mainPath)}`
);
createFile(
`apps/${appName}/postcss.config.js`,
`
console.log('HELLO FROM APP'); // need this output for e2e test
module.exports = {};
`
);
createFile(
`libs/${libName}/postcss.config.js`,
`
console.log('HELLO FROM LIB'); // need this output for e2e test
module.exports = {};
`
);
let buildResults = await runCLIAsync(`build ${appName}`);
expect(buildResults.combinedOutput).toMatch(/HELLO FROM APP/);
expect(buildResults.combinedOutput).toMatch(/HELLO FROM LIB/);
// Only load app PostCSS config
updateJson(`apps/${appName}/project.json`, (json) => {
json.targets.build.options.postcssConfig = `apps/${appName}/postcss.config.js`;
return json;
});
buildResults = await runCLIAsync(`build ${appName}`);
expect(buildResults.combinedOutput).toMatch(/HELLO FROM APP/);
expect(buildResults.combinedOutput).not.toMatch(/HELLO FROM LIB/);
}, 250_000);
});
});
async function testGeneratedApp(
appName,
opts: {
checkStyles: boolean;
checkLinter: boolean;
checkE2E: boolean;
checkSourceMap?: boolean;
}
) {
if (opts.checkLinter) {
const lintResults = runCLI(`lint ${appName}`);
expect(lintResults).toContain('All files pass linting.');
}
runCLI(
`build ${appName} --outputHashing none ${
opts.checkSourceMap ? '--sourceMap' : ''
}`
);
const filesToCheck = [
`dist/apps/${appName}/index.html`,
`dist/apps/${appName}/runtime.js`,
`dist/apps/${appName}/main.js`,
];
if (opts.checkSourceMap) {
filesToCheck.push(`dist/apps/${appName}/main.js.map`);
}
if (opts.checkStyles) {
filesToCheck.push(`dist/apps/${appName}/styles.css`);
}
checkFilesExist(...filesToCheck);
if (opts.checkStyles) {
expect(readFile(`dist/apps/${appName}/index.html`)).toContain(
'<link rel="stylesheet" href="styles.css">'
);
}
const testResults = await runCLIAsync(`test ${appName}`);
expect(testResults.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
if (opts.checkE2E && runE2ETests()) {
const e2eResults = runCLI(`e2e ${appName}-e2e --no-watch`);
expect(e2eResults).toContain('All specs passed!');
expect(await killPorts()).toBeTruthy();
}
}
|
2,027 | 0 | petrpan-code/nrwl/nx/e2e/react-extensions | petrpan-code/nrwl/nx/e2e/react-extensions/src/cypress-component-tests.test.ts | import {
cleanupProject,
createFile,
ensureCypressInstallation,
newProject,
runCLI,
runE2ETests,
uniq,
updateFile,
updateJson,
} from '../../utils';
import { join } from 'path';
describe('React Cypress Component Tests', () => {
let projectName;
const appName = uniq('cy-react-app');
const usedInAppLibName = uniq('cy-react-lib');
const buildableLibName = uniq('cy-react-buildable-lib');
beforeAll(async () => {
projectName = newProject({ name: uniq('cy-react') });
ensureCypressInstallation();
runCLI(
`generate @nx/react:app ${appName} --bundler=webpack --no-interactive`
);
updateJson('nx.json', (json) => ({
...json,
generators: {
...json.generators,
'@nx/react': {
library: {
unitTestRunner: 'jest',
},
},
},
}));
runCLI(
`generate @nx/react:component fancy-cmp --project=${appName} --no-interactive`
);
runCLI(
`generate @nx/react:lib ${usedInAppLibName} --no-interactive --unitTestRunner=jest`
);
runCLI(
`generate @nx/react:component btn --project=${usedInAppLibName} --export --no-interactive`
);
// makes sure custom webpack is loading
createFile(
`apps/${appName}/src/assets/demo.svg`,
`
<svg version="1.1"
width="300" height="200"
xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="aliceblue" />
<circle cx="150" cy="100" r="80" fill="blue" />
<text x="150" y="125" font-size="60" text-anchor="middle" fill="white">nrwl</text>
</svg>
`
);
updateFile(
`libs/${usedInAppLibName}/src/lib/btn/btn.tsx`,
`
import styles from './btn.module.css';
/* eslint-disable-next-line */
export interface BtnProps {
text: string
}
export function Btn(props: BtnProps) {
return (
<div className={styles['container']}>
<h1>Welcome to Btn!</h1>
<button className="text-green-500">{props.text}</button>
</div>
);
}
export default Btn;
`
);
updateFile(
`apps/${appName}/src/app/app.tsx`,
`
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import styles from './app.module.css';
import logo from '../assets/demo.svg';
import { Btn } from '@${projectName}/${usedInAppLibName}';
export function App() {
return (
<>
<Btn text={'I am the app'}/>
<img src={logo} alt="logo" />
</>
);
}
export default App;`
);
runCLI(
`generate @nx/react:lib ${buildableLibName} --buildable --no-interactive --unitTestRunner=jest`
);
runCLI(
`generate @nx/react:component input --project=${buildableLibName} --export --no-interactive`
);
updateFile(
`libs/${buildableLibName}/src/lib/input/input.tsx`,
`
import styles from './input.module.css';
/* eslint-disable-next-line */
export interface InputProps {
readOnly: boolean
}
export function Input(props: InputProps) {
return (
<label className="text-green-500">Email:
<input className="border-blue-500" type="email" readOnly={props.readOnly}/>
</label>
);
}
export default Input;
`
);
createFile('libs/assets/data.json', JSON.stringify({ data: 'data' }));
updateJson(join('apps', appName, 'project.json'), (config) => {
config.targets['build'].options.assets.push({
glob: '**/*',
input: 'libs/assets',
output: 'assets',
});
return config;
});
});
afterAll(() => cleanupProject());
it('should test app', () => {
runCLI(
`generate @nx/react:cypress-component-configuration --project=${appName} --generate-tests`
);
if (runE2ETests()) {
expect(runCLI(`component-test ${appName} --no-watch`)).toContain(
'All specs passed!'
);
}
}, 300_000);
it('should successfully component test lib being used in app', () => {
runCLI(
`generate @nx/react:cypress-component-configuration --project=${usedInAppLibName} --generate-tests`
);
if (runE2ETests()) {
expect(runCLI(`component-test ${usedInAppLibName} --no-watch`)).toContain(
'All specs passed!'
);
}
}, 300_000);
it('should successfully component test lib being used in app using babel compiler', () => {
runCLI(
`generate @nx/react:cypress-component-configuration --project=${usedInAppLibName} --generate-tests`
);
updateFile(`libs/${usedInAppLibName}/cypress.config.ts`, (content) => {
// apply babel compiler
return content.replace(
'nxComponentTestingPreset(__filename)',
'nxComponentTestingPreset(__filename, {compiler: "babel"})'
);
});
if (runE2ETests()) {
expect(runCLI(`component-test ${usedInAppLibName} --no-watch`)).toContain(
'All specs passed!'
);
}
}, 300_000);
it('should test buildable lib not being used in app', () => {
createFile(
`libs/${buildableLibName}/src/lib/input/input.cy.tsx`,
`
import * as React from 'react'
import Input from './input'
describe(Input.name, () => {
it('renders', () => {
cy.mount(<Input readOnly={false} />)
cy.get('label').should('have.css', 'color', 'rgb(0, 0, 0)');
})
it('should be read only', () => {
cy.mount(<Input readOnly={true}/>)
cy.get('input').should('have.attr', 'readonly');
})
});
`
);
runCLI(
`generate @nx/react:cypress-component-configuration --project=${buildableLibName} --generate-tests --build-target=${appName}:build`
);
if (runE2ETests()) {
expect(runCLI(`component-test ${buildableLibName} --no-watch`)).toContain(
'All specs passed!'
);
}
// add tailwind
runCLI(`generate @nx/react:setup-tailwind --project=${buildableLibName}`);
updateFile(
`libs/${buildableLibName}/src/styles.css`,
`
@tailwind components;
@tailwind base;
@tailwind utilities;
`
);
updateFile(
`libs/${buildableLibName}/src/lib/input/input.cy.tsx`,
(content) => {
// text-green-500 should now apply
return content.replace('rgb(0, 0, 0)', 'rgb(34, 197, 94)');
}
);
updateFile(
`libs/${buildableLibName}/src/lib/input/input.tsx`,
(content) => {
return `import '../../styles.css';
${content}`;
}
);
if (runE2ETests()) {
expect(runCLI(`component-test ${buildableLibName} --no-watch`)).toContain(
'All specs passed!'
);
}
}, 300_000);
it('should work with async webpack config', async () => {
// TODO: (caleb) for whatever reason the MF webpack config + CT is running, but cypress is not starting up?
// are they overriding some option on top of each other causing cypress to not see it's running?
createFile(
`apps/${appName}/webpack.config.js`,
`
const { composePlugins, withNx } = require('@nx/webpack');
const { withReact } = require('@nx/react');
module.exports = composePlugins(
withNx(),
withReact(),
async function (configuration) {
await new Promise((res) => {
setTimeout(() => {
console.log('I am from the custom async Webpack config');
res();
}, 1000);
});
return configuration;
}
);
`
);
updateJson(join('apps', appName, 'project.json'), (config) => {
config.targets[
'build'
].options.webpackConfig = `apps/${appName}/webpack.config.js`;
return config;
});
if (runE2ETests()) {
const results = runCLI(`component-test ${appName}`);
expect(results).toContain('I am from the custom async Webpack config');
expect(results).toContain('All specs passed!');
}
});
// flaky bc of upstream issue https://github.com/cypress-io/cypress/issues/25913
it.skip('should CT vite projects importing other projects', () => {
const viteLibName = uniq('vite-lib');
runCLI(
`generate @nrwl/react:lib ${viteLibName} --bundler=vite --no-interactive`
);
updateFile(`libs/${viteLibName}/src/lib/${viteLibName}.tsx`, () => {
return `import { Btn } from '@${projectName}/${usedInAppLibName}';
export function MyComponent() {
return (
<>
<Btn text={'I am the app'}/>
<p>hello</p>
</>
);
}
export default MyComponent;`;
});
runCLI(
`generate @nrwl/react:cypress-component-configuration --project=${viteLibName} --generate-tests --bundler=vite --build-target=${appName}:build`
);
if (runE2ETests()) {
expect(runCLI(`component-test ${viteLibName}`)).toContain(
'All specs passed!'
);
}
});
});
|
2,028 | 0 | petrpan-code/nrwl/nx/e2e/react-extensions | petrpan-code/nrwl/nx/e2e/react-extensions/src/react-vite.test.ts | import {
checkFilesExist,
cleanupProject,
newProject,
readJson,
runCLI,
runCLIAsync,
uniq,
} from '@nx/e2e/utils';
describe('Build React applications and libraries with Vite', () => {
let proj: string;
beforeEach(() => {
proj = newProject();
});
afterAll(() => {
cleanupProject();
});
it('should test and lint app with bundler=vite and compiler=babel', async () => {
const viteApp = uniq('viteapp');
runCLI(
`generate @nx/react:app ${viteApp} --bundler=vite --compiler=babel --unitTestRunner=vitest --no-interactive`
);
const appTestResults = await runCLIAsync(`test ${viteApp}`);
expect(appTestResults.combinedOutput).toContain(
'Successfully ran target test'
);
const appLintResults = await runCLIAsync(`lint ${viteApp}`);
expect(appLintResults.combinedOutput).toContain(
'Successfully ran target lint'
);
await runCLIAsync(`build ${viteApp}`);
checkFilesExist(`dist/apps/${viteApp}/index.html`);
}, 300_000);
it('should test and lint app with bundler=vite and compiler=swc', async () => {
const viteApp = uniq('viteapp');
runCLI(
`generate @nx/react:app ${viteApp} --bundler=vite --compiler=swc --unitTestRunner=vitest --no-interactive`
);
const appTestResults = await runCLIAsync(`test ${viteApp}`);
expect(appTestResults.combinedOutput).toContain(
'Successfully ran target test'
);
const appLintResults = await runCLIAsync(`lint ${viteApp}`);
expect(appLintResults.combinedOutput).toContain(
'Successfully ran target lint'
);
await runCLIAsync(`build ${viteApp}`);
checkFilesExist(`dist/apps/${viteApp}/index.html`);
}, 300_000);
it('should test and lint app with bundler=vite and inSourceTests', async () => {
const viteApp = uniq('viteapp');
const viteLib = uniq('vitelib');
runCLI(
`generate @nx/react:app ${viteApp} --bundler=vite --unitTestRunner=vitest --inSourceTests --no-interactive`
);
expect(() => {
checkFilesExist(`apps/${viteApp}/src/app/app.spec.tsx`);
}).toThrow();
const appTestResults = await runCLIAsync(`test ${viteApp}`);
expect(appTestResults.combinedOutput).toContain(
'Successfully ran target test'
);
const appLintResults = await runCLIAsync(`lint ${viteApp}`);
expect(appLintResults.combinedOutput).toContain(
'Successfully ran target lint'
);
await runCLIAsync(`build ${viteApp}`);
checkFilesExist(`dist/apps/${viteApp}/index.html`);
runCLI(
`generate @nx/react:lib ${viteLib} --bundler=vite --inSourceTests --unitTestRunner=vitest --no-interactive`
);
expect(() => {
checkFilesExist(`libs/${viteLib}/src/lib/${viteLib}.spec.tsx`);
}).toThrow();
runCLI(
`generate @nx/react:component comp1 --inSourceTests --export --project=${viteLib} --no-interactive`
);
expect(() => {
checkFilesExist(`libs/${viteLib}/src/lib/comp1/comp1.spec.tsx`);
}).toThrow();
runCLI(
`generate @nx/react:component comp2 --export --project=${viteLib} --no-interactive`
);
checkFilesExist(`libs/${viteLib}/src/lib/comp2/comp2.spec.tsx`);
const libTestResults = await runCLIAsync(`test ${viteLib}`);
expect(libTestResults.combinedOutput).toContain(
'Successfully ran target test'
);
const libLintResults = await runCLIAsync(`lint ${viteLib}`);
expect(libLintResults.combinedOutput).toContain(
'Successfully ran target lint'
);
await runCLIAsync(`build ${viteLib}`);
checkFilesExist(
`dist/libs/${viteLib}/index.d.ts`,
`dist/libs/${viteLib}/index.js`,
`dist/libs/${viteLib}/index.mjs`
);
}, 300_000);
it('should support bundling with Vite', async () => {
const viteLib = uniq('vitelib');
runCLI(
`generate @nx/react:lib ${viteLib} --bundler=vite --no-interactive --unit-test-runner=none`
);
const packageJson = readJson('package.json');
// Vite does not need these libraries to work.
expect(packageJson.dependencies['core-js']).toBeUndefined();
expect(packageJson.dependencies['tslib']).toBeUndefined();
await runCLIAsync(`build ${viteLib}`);
checkFilesExist(
`dist/libs/${viteLib}/package.json`,
`dist/libs/${viteLib}/index.d.ts`,
`dist/libs/${viteLib}/index.js`,
`dist/libs/${viteLib}/index.mjs`
);
// Convert non-buildable lib to buildable one
const nonBuildableLib = uniq('nonbuildablelib');
runCLI(
`generate @nx/react:lib ${nonBuildableLib} --no-interactive --unitTestRunner=jest`
);
runCLI(
`generate @nx/vite:configuration ${nonBuildableLib} --uiFramework=react --no-interactive`
);
await runCLIAsync(`build ${nonBuildableLib}`);
checkFilesExist(
`dist/libs/${nonBuildableLib}/index.d.ts`,
`dist/libs/${nonBuildableLib}/index.js`,
`dist/libs/${nonBuildableLib}/index.mjs`
);
}, 300_000);
});
|
2,033 | 0 | petrpan-code/nrwl/nx/e2e/react-native | petrpan-code/nrwl/nx/e2e/react-native/src/react-native.test.ts | import {
checkFilesExist,
cleanupProject,
expectTestsPass,
getPackageManagerCommand,
isOSX,
killPorts,
newProject,
promisifiedTreeKill,
readJson,
runCLI,
runCLIAsync,
runCommand,
runCommandUntil,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { ChildProcess } from 'child_process';
import { join } from 'path';
describe('react native', () => {
let proj: string;
let appName = uniq('my-app');
let libName = uniq('lib');
beforeAll(() => {
proj = newProject();
// we create empty preset above which skips creation of `production` named input
updateJson('nx.json', (nxJson) => {
nxJson.namedInputs = {
default: ['{projectRoot}/**/*', 'sharedGlobals'],
production: ['default'],
sharedGlobals: [],
};
nxJson.targetDefaults.build.inputs = ['production', '^production'];
return nxJson;
});
runCLI(
`generate @nx/react-native:application ${appName} --install=false --no-interactive`
);
runCLI(
`generate @nx/react-native:library ${libName} --buildable --publishable --importPath=${proj}/${libName} --no-interactive`
);
});
afterAll(() => cleanupProject());
it('should test and lint', async () => {
const componentName = uniq('Component');
runCLI(
`generate @nx/react-native:component ${componentName} --project=${libName} --export --no-interactive`
);
updateFile(`apps/${appName}/src/app/App.tsx`, (content) => {
let updated = `// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport {${componentName}} from '${proj}/${libName}';\n${content}`;
return updated;
});
expectTestsPass(await runCLIAsync(`test ${appName}`));
expectTestsPass(await runCLIAsync(`test ${libName}`));
const appLintResults = await runCLIAsync(`lint ${appName}`);
expect(appLintResults.combinedOutput).toContain('All files pass linting.');
const libLintResults = await runCLIAsync(`lint ${libName}`);
expect(libLintResults.combinedOutput).toContain('All files pass linting.');
});
it('should bundle-ios', async () => {
const iosBundleResult = await runCLIAsync(
`bundle-ios ${appName} --sourcemapOutput=../../dist/apps/${appName}/ios/main.map`
);
expect(iosBundleResult.combinedOutput).toContain(
'Done writing bundle output'
);
expect(() => {
checkFilesExist(`dist/apps/${appName}/ios/main.jsbundle`);
checkFilesExist(`dist/apps/${appName}/ios/main.map`);
}).not.toThrow();
});
it('should bundle-android', async () => {
const androidBundleResult = await runCLIAsync(
`bundle-android ${appName} --sourcemapOutput=../../dist/apps/${appName}/android/main.map`
);
expect(androidBundleResult.combinedOutput).toContain(
'Done writing bundle output'
);
expect(() => {
checkFilesExist(`dist/apps/${appName}/android/main.jsbundle`);
checkFilesExist(`dist/apps/${appName}/android/main.map`);
}).not.toThrow();
});
it('should start', async () => {
let process: ChildProcess;
const port = 8081;
try {
process = await runCommandUntil(
`start ${appName} --interactive=false --port=${port}`,
(output) => {
return (
output.includes(`Packager is ready at http://localhost::${port}`) ||
output.includes('Starting JS server...')
);
}
);
} catch (err) {
console.error(err);
}
// port and process cleanup
try {
if (process && process.pid) {
await promisifiedTreeKill(process.pid, 'SIGKILL');
await killPorts(port);
}
} catch (err) {
expect(err).toBeFalsy();
}
});
if (isOSX()) {
// TODO(@meeroslav): this test is causing git-hasher to overflow with arguments. Enable when it's fixed.
xit('should pod install', async () => {
expect(async () => {
await runCLIAsync(`pod-install ${appName}`);
checkFilesExist(`apps/${appName}/ios/Podfile.lock`);
}).not.toThrow();
});
}
it('should create storybook with application', async () => {
runCLI(
`generate @nx/react-native:storybook-configuration ${appName} --generateStories --no-interactive`
);
expect(() =>
checkFilesExist(
`.storybook/story-loader.ts`,
`apps/${appName}/src/storybook/storybook.ts`,
`apps/${appName}/src/storybook/toggle-storybook.tsx`,
`apps/${appName}/src/app/App.stories.tsx`
)
).not.toThrow();
await runCLIAsync(`storybook ${appName}`);
const result = readJson(join('apps', appName, 'package.json'));
expect(result).toMatchObject({
dependencies: {
'@storybook/addon-ondevice-actions': '*',
'@storybook/addon-ondevice-backgrounds': '*',
'@storybook/addon-ondevice-controls': '*',
'@storybook/addon-ondevice-notes': '*',
},
});
});
it('should upgrade native for application', async () => {
expect(() =>
runCLI(
`generate @nx/react-native:upgrade-native ${appName} --install=false`
)
).not.toThrow();
});
it('should build publishable library', async () => {
const componentName = uniq('Component');
runCLI(
`generate @nx/react-native:component ${componentName} --project=${libName} --export`
);
expect(() => {
runCLI(`build ${libName}`);
checkFilesExist(`dist/libs/${libName}/index.esm.js`);
checkFilesExist(`dist/libs/${libName}/src/index.d.ts`);
}).not.toThrow();
});
it('sync npm dependencies for autolink', async () => {
// Add npm package with native modules
updateFile(join('package.json'), (content) => {
const json = JSON.parse(content);
json.dependencies['react-native-image-picker'] = '5.3.1';
json.dependencies['@react-native-async-storage/async-storage'] = '1.18.1';
return JSON.stringify(json, null, 2);
});
runCommand(`${getPackageManagerCommand().install}`);
// Add import for Nx to pick up
updateFile(join('apps', appName, 'src/app/App.tsx'), (content) => {
return `import AsyncStorage from '@react-native-async-storage/async-storage';${content}`;
});
await runCLIAsync(
`sync-deps ${appName} --include=react-native-image-picker`
);
const result = readJson(join('apps', appName, 'package.json'));
expect(result).toMatchObject({
dependencies: {
'react-native-image-picker': '*',
'react-native': '*',
'@react-native-async-storage/async-storage': '*',
},
});
});
it('should tsc app', async () => {
expect(() => {
const pmc = getPackageManagerCommand();
runCommand(
`${pmc.runUninstalledPackage} tsc -p apps/${appName}/tsconfig.app.json`
);
checkFilesExist(
`dist/out-tsc/apps/${appName}/src/main.js`,
`dist/out-tsc/apps/${appName}/src/main.d.ts`,
`dist/out-tsc/apps/${appName}/src/app/App.js`,
`dist/out-tsc/apps/${appName}/src/app/App.d.ts`,
`dist/out-tsc/libs/${libName}/src/index.js`,
`dist/out-tsc/libs/${libName}/src/index.d.ts`
);
}).not.toThrow();
});
it('should support generating projects with the new name and root format', () => {
const appName = uniq('app1');
const libName = uniq('@my-org/lib1');
runCLI(
`generate @nx/react-native:application ${appName} --project-name-and-root-format=as-provided --no-interactive`
);
// check files are generated without the layout directory ("apps/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${appName}/src/app/App.tsx`);
// check tests pass
const appTestResult = runCLI(`test ${appName}`);
expect(appTestResult).toContain(
`Successfully ran target test for project ${appName}`
);
// assert scoped project names are not supported when --project-name-and-root-format=derived
expect(() =>
runCLI(
`generate @nx/react-native:library ${libName} --buildable --project-name-and-root-format=derived`
)
).toThrow();
runCLI(
`generate @nx/react-native:library ${libName} --buildable --project-name-and-root-format=as-provided`
);
// check files are generated without the layout directory ("libs/") and
// using the project name as the directory when no directory is provided
checkFilesExist(`${libName}/src/index.ts`);
// check tests pass
const libTestResult = runCLI(`test ${libName}`);
expect(libTestResult).toContain(
`Successfully ran target test for project ${libName}`
);
});
});
|
2,038 | 0 | petrpan-code/nrwl/nx/e2e/release | petrpan-code/nrwl/nx/e2e/release/src/independent-projects.test.ts | import { joinPathFragments } from '@nx/devkit';
import {
cleanupProject,
exists,
newProject,
readFile,
runCLI,
runCommand,
tmpProjPath,
uniq,
updateJson,
} from '@nx/e2e/utils';
expect.addSnapshotSerializer({
serialize(str: string) {
return (
str
// Remove all output unique to specific projects to ensure deterministic snapshots
.replaceAll(`/private/${tmpProjPath()}`, '')
.replaceAll(tmpProjPath(), '')
.replaceAll('/private/', '')
.replaceAll(/my-pkg-\d+/g, '{project-name}')
.replaceAll(
/integrity:\s*.*/g,
'integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
)
.replaceAll(/\b[0-9a-f]{40}\b/g, '{SHASUM}')
.replaceAll(/\d*B index\.js/g, 'XXB index.js')
.replaceAll(/\d*B project\.json/g, 'XXB project.json')
.replaceAll(/\d*B package\.json/g, 'XXXB package.json')
.replaceAll(/size:\s*\d*\s?B/g, 'size: XXXB')
.replaceAll(/\d*\.\d*\s?kB/g, 'XXX.XXX kb')
// We trim each line to reduce the chances of snapshot flakiness
.split('\n')
.map((r) => r.trim())
.join('\n')
);
},
test(val: string) {
return val != null && typeof val === 'string';
},
});
describe('nx release - independent projects', () => {
let pkg1: string;
let pkg2: string;
let pkg3: string;
beforeAll(() => {
newProject({
unsetProjectNameAndRootFormat: false,
});
pkg1 = uniq('my-pkg-1');
runCLI(`generate @nx/workspace:npm-package ${pkg1}`);
pkg2 = uniq('my-pkg-2');
runCLI(`generate @nx/workspace:npm-package ${pkg2}`);
pkg3 = uniq('my-pkg-3');
runCLI(`generate @nx/workspace:npm-package ${pkg3}`);
updateJson(`${pkg3}/package.json`, (json) => {
json.private = true;
return json;
});
/**
* Update pkg2 to depend on pkg3.
*/
updateJson(`${pkg2}/package.json`, (json) => {
json.dependencies ??= {};
json.dependencies[`@proj/${pkg3}`] = '0.0.0';
return json;
});
// Normalize git committer information so it is deterministic in snapshots
runCommand(`git config user.email "[email protected]"`);
runCommand(`git config user.name "Test"`);
// Create a baseline version tag for each project
runCommand(`git tag ${pkg1}@0.0.0`);
runCommand(`git tag ${pkg2}@0.0.0`);
runCommand(`git tag ${pkg3}@0.0.0`);
});
afterAll(() => cleanupProject());
describe('version', () => {
beforeEach(() => {
/**
* Configure independent releases in the most minimal way possible.
*/
updateJson('nx.json', () => {
return {
release: {
projectsRelationship: 'independent',
},
};
});
});
it('should allow versioning projects independently', async () => {
const versionPkg1Output = runCLI(
`release version 999.9.9-package.1 -p ${pkg1}`
);
expect(versionPkg1Output).toMatchInlineSnapshot(`
> NX Your filter "{project-name}" matched the following projects:
- {project-name}
> NX Running release version for project: {project-name}
{project-name} π Reading data for package "@proj/{project-name}" from {project-name}/package.json
{project-name} π Resolved the current version as 0.0.0 from {project-name}/package.json
{project-name} π Using the provided version specifier "999.9.9-package.1".
{project-name} βοΈ New version 999.9.9-package.1 written to {project-name}/package.json
"name": "@proj/{project-name}",
- "version": "0.0.0",
+ "version": "999.9.9-package.1",
"scripts": {
`);
const versionPkg2Output = runCLI(
`release version 999.9.9-package.2 -p ${pkg2}`
);
expect(versionPkg2Output).toMatchInlineSnapshot(`
> NX Your filter "{project-name}" matched the following projects:
- {project-name}
> NX Running release version for project: {project-name}
{project-name} π Reading data for package "@proj/{project-name}" from {project-name}/package.json
{project-name} π Resolved the current version as 0.0.0 from {project-name}/package.json
{project-name} π Using the provided version specifier "999.9.9-package.2".
{project-name} βοΈ New version 999.9.9-package.2 written to {project-name}/package.json
"name": "@proj/{project-name}",
- "version": "0.0.0",
+ "version": "999.9.9-package.2",
"scripts": {
}
+
`);
const versionPkg3Output = runCLI(
`release version 999.9.9-package.3 -p ${pkg3}`
);
expect(versionPkg3Output).toMatchInlineSnapshot(`
> NX Your filter "{project-name}" matched the following projects:
- {project-name}
> NX Running release version for project: {project-name}
{project-name} π Reading data for package "@proj/{project-name}" from {project-name}/package.json
{project-name} π Resolved the current version as 0.0.0 from {project-name}/package.json
{project-name} π Using the provided version specifier "999.9.9-package.3".
{project-name} βοΈ New version 999.9.9-package.3 written to {project-name}/package.json
{project-name} βοΈ Applying new version 999.9.9-package.3 to 1 package which depends on {project-name}
"name": "@proj/{project-name}",
- "version": "0.0.0",
+ "version": "999.9.9-package.3",
"scripts": {
}
+
"dependencies": {
- "@proj/{project-name}": "0.0.0"
+ "@proj/{project-name}": "999.9.9-package.3"
}
`);
}, 500000);
it('should support automated git operations after versioning when configured', async () => {
const headSHA = runCommand(`git rev-parse HEAD`).trim();
runCLI(
`release version 999.9.9-version-git-operations-test.1 -p ${pkg1}`
);
// No git operations should have been performed by the previous command because not yet configured in nx.json nor passed as a flag
expect(runCommand(`git rev-parse HEAD`).trim()).toEqual(headSHA);
// Enable git commit and tag operations via CLI flags
const versionWithGitActionsCLIOutput = runCLI(
`release version 999.9.9-version-git-operations-test.2 -p ${pkg1} --git-commit --git-tag --verbose` // add verbose so we get richer output
);
expect(versionWithGitActionsCLIOutput).toMatchInlineSnapshot(`
> NX Your filter "{project-name}" matched the following projects:
- {project-name}
> NX Running release version for project: {project-name}
{project-name} π Reading data for package "@proj/{project-name}" from {project-name}/package.json
{project-name} π Resolved the current version as 999.9.9-version-git-operations-test.1 from {project-name}/package.json
{project-name} π Using the provided version specifier "999.9.9-version-git-operations-test.2".
{project-name} βοΈ New version 999.9.9-version-git-operations-test.2 written to {project-name}/package.json
"name": "@proj/{project-name}",
- "version": "999.9.9-version-git-operations-test.1",
+ "version": "999.9.9-version-git-operations-test.2",
"scripts": {
> NX Committing changes with git
Staging files in git with the following command:
git add {project-name}/package.json
Committing files in git with the following command:
git commit --message chore(release): publish --message - project: {project-name} 999.9.9-version-git-operations-test.2
> NX Tagging commit with git
Tagging the current commit in git with the following command:
git tag --annotate {project-name}@999.9.9-version-git-operations-test.2 --message {project-name}@999.9.9-version-git-operations-test.2
`);
// Ensure the git operations were performed
expect(runCommand(`git rev-parse HEAD`).trim()).not.toEqual(headSHA);
// Commit
expect(runCommand(`git --no-pager log -1 --pretty=format:%B`).trim())
.toMatchInlineSnapshot(`
chore(release): publish
- project: {project-name} 999.9.9-version-git-operations-test.2
`);
// Tags
expect(runCommand('git tag --points-at HEAD')).toMatchInlineSnapshot(`
{project-name}@999.9.9-version-git-operations-test.2
`);
// Enable git commit and tag operations for the version command via config
updateJson('nx.json', (json) => {
return {
...json,
release: {
...json.release,
version: {
...json.release.version,
git: {
commit: true,
tag: true,
},
},
// Configure multiple release groups with different relationships to capture differences in commit body
groups: {
independent: {
projects: [pkg1, pkg2],
projectsRelationship: 'independent',
},
fixed: {
projects: [pkg3],
projectsRelationship: 'fixed',
},
},
},
};
});
const versionWithGitActionsConfigOutput = runCLI(
`release version 999.9.9-version-git-operations-test.3 --verbose` // add verbose so we get richer output
);
expect(versionWithGitActionsConfigOutput).toMatchInlineSnapshot(`
> NX Running release version for project: {project-name}
{project-name} π Reading data for package "@proj/{project-name}" from {project-name}/package.json
{project-name} π Resolved the current version as 999.9.9-version-git-operations-test.2 from {project-name}/package.json
{project-name} π Using the provided version specifier "999.9.9-version-git-operations-test.3".
{project-name} βοΈ New version 999.9.9-version-git-operations-test.3 written to {project-name}/package.json
> NX Running release version for project: {project-name}
{project-name} π Reading data for package "@proj/{project-name}" from {project-name}/package.json
{project-name} π Resolved the current version as 999.9.9-package.2 from {project-name}/package.json
{project-name} π Using the provided version specifier "999.9.9-version-git-operations-test.3".
{project-name} βοΈ New version 999.9.9-version-git-operations-test.3 written to {project-name}/package.json
> NX Running release version for project: {project-name}
{project-name} π Reading data for package "@proj/{project-name}" from {project-name}/package.json
{project-name} π Resolved the current version as 999.9.9-package.3 from {project-name}/package.json
{project-name} π Using the provided version specifier "999.9.9-version-git-operations-test.3".
{project-name} βοΈ New version 999.9.9-version-git-operations-test.3 written to {project-name}/package.json
"name": "@proj/{project-name}",
- "version": "999.9.9-version-git-operations-test.2",
+ "version": "999.9.9-version-git-operations-test.3",
"scripts": {
"name": "@proj/{project-name}",
- "version": "999.9.9-package.2",
+ "version": "999.9.9-version-git-operations-test.3",
"scripts": {
"name": "@proj/{project-name}",
- "version": "999.9.9-package.3",
+ "version": "999.9.9-version-git-operations-test.3",
"scripts": {
> NX Committing changes with git
Staging files in git with the following command:
git add {project-name}/package.json {project-name}/package.json {project-name}/package.json
Committing files in git with the following command:
git commit --message chore(release): publish --message - project: {project-name} 999.9.9-version-git-operations-test.3 --message - project: {project-name} 999.9.9-version-git-operations-test.3 --message - release-group: fixed 999.9.9-version-git-operations-test.3
> NX Tagging commit with git
Tagging the current commit in git with the following command:
git tag --annotate {project-name}@999.9.9-version-git-operations-test.3 --message {project-name}@999.9.9-version-git-operations-test.3
Tagging the current commit in git with the following command:
git tag --annotate {project-name}@999.9.9-version-git-operations-test.3 --message {project-name}@999.9.9-version-git-operations-test.3
Tagging the current commit in git with the following command:
git tag --annotate v999.9.9-version-git-operations-test.3 --message v999.9.9-version-git-operations-test.3
`);
// Ensure the git operations were performed
expect(runCommand(`git rev-parse HEAD`).trim()).not.toEqual(headSHA);
// Commit
expect(runCommand(`git --no-pager log -1 --pretty=format:%B`).trim())
.toMatchInlineSnapshot(`
chore(release): publish
- project: {project-name} 999.9.9-version-git-operations-test.3
- project: {project-name} 999.9.9-version-git-operations-test.3
- release-group: fixed 999.9.9-version-git-operations-test.3
`);
// Tags
expect(runCommand('git tag --points-at HEAD')).toMatchInlineSnapshot(`
{project-name}@999.9.9-version-git-operations-test.3
{project-name}@999.9.9-version-git-operations-test.3
v999.9.9-version-git-operations-test.3
`);
});
});
describe('changelog', () => {
beforeEach(() => {
updateJson('nx.json', () => {
return {
release: {
projectsRelationship: 'independent',
changelog: {
projectChangelogs: {}, // enable project changelogs with default options
workspaceChangelog: false, // disable workspace changelog
},
},
};
});
});
it('should allow generating changelogs for projects independently', async () => {
// pkg1
const changelogPkg1Output = runCLI(
`release changelog 999.9.9-package.1 -p ${pkg1} --dry-run`
);
expect(changelogPkg1Output).toMatchInlineSnapshot(`
> NX Your filter "{project-name}" matched the following projects:
- {project-name}
> NX Previewing an entry in {project-name}/CHANGELOG.md for {project-name}@999.9.9-package.1
+ ## 999.9.9-package.1
+
+ This was a version bump only for {project-name} to align it with other projects, there were no code changes.
`);
// pkg2
const changelogPkg2Output = runCLI(
`release changelog 999.9.9-package.2 -p ${pkg2} --dry-run`
);
expect(changelogPkg2Output).toMatchInlineSnapshot(`
> NX Your filter "{project-name}" matched the following projects:
- {project-name}
> NX Previewing an entry in {project-name}/CHANGELOG.md for {project-name}@999.9.9-package.2
+ ## 999.9.9-package.2
+
+ This was a version bump only for {project-name} to align it with other projects, there were no code changes.
`);
// pkg3
const changelogPkg3Output = runCLI(
`release changelog 999.9.9-package.3 -p ${pkg3} --dry-run`
);
expect(changelogPkg3Output).toMatchInlineSnapshot(`
> NX Your filter "{project-name}" matched the following projects:
- {project-name}
> NX Previewing an entry in {project-name}/CHANGELOG.md for {project-name}@999.9.9-package.3
+ ## 999.9.9-package.3
+
+ This was a version bump only for {project-name} to align it with other projects, there were no code changes.
`);
}, 500000);
it('should support automated git operations after changelog when configured', async () => {
// No project changelog yet
expect(exists(joinPathFragments(pkg1, 'CHANGELOG.md'))).toEqual(false);
const headSHA = runCommand(`git rev-parse HEAD`).trim();
runCLI(
`release changelog 999.9.9-changelog-git-operations-test.1 -p ${pkg1}`
);
// No git operations should have been performed by the previous command because not yet configured in nx.json nor passed as a flag
expect(runCommand(`git rev-parse HEAD`).trim()).toEqual(headSHA);
expect(readFile(joinPathFragments(pkg1, 'CHANGELOG.md')))
.toMatchInlineSnapshot(`
## 999.9.9-changelog-git-operations-test.1
This was a version bump only for {project-name} to align it with other projects, there were no code changes.
`);
// Enable git commit and tag operations via CLI flags
const versionWithGitActionsCLIOutput = runCLI(
`release changelog 999.9.9-changelog-git-operations-test.2 -p ${pkg1} --git-commit --git-tag --verbose` // add verbose so we get richer output
);
expect(versionWithGitActionsCLIOutput).toMatchInlineSnapshot(`
> NX Your filter "{project-name}" matched the following projects:
- {project-name}
> NX Generating an entry in {project-name}/CHANGELOG.md for {project-name}@999.9.9-changelog-git-operations-test.2
+ ## 999.9.9-changelog-git-operations-test.2
+
+ This was a version bump only for {project-name} to align it with other projects, there were no code changes.
+
## 999.9.9-changelog-git-operations-test.1
This was a version bump only for {project-name} to align it with other projects, there were no code changes.
> NX Committing changes with git
Staging files in git with the following command:
git add {project-name}/CHANGELOG.md
Committing files in git with the following command:
git commit --message chore(release): publish --message - project: {project-name} 999.9.9-changelog-git-operations-test.2
> NX Tagging commit with git
Tagging the current commit in git with the following command:
git tag --annotate {project-name}@999.9.9-changelog-git-operations-test.2 --message {project-name}@999.9.9-changelog-git-operations-test.2
`);
// Ensure the git operations were performed
expect(runCommand(`git rev-parse HEAD`).trim()).not.toEqual(headSHA);
// Commit
expect(runCommand(`git --no-pager log -1 --pretty=format:%B`).trim())
.toMatchInlineSnapshot(`
chore(release): publish
- project: {project-name} 999.9.9-changelog-git-operations-test.2
`);
// Tags
expect(runCommand('git tag --points-at HEAD')).toMatchInlineSnapshot(`
{project-name}@999.9.9-changelog-git-operations-test.2
`);
expect(readFile(joinPathFragments(pkg1, 'CHANGELOG.md')))
.toMatchInlineSnapshot(`
## 999.9.9-changelog-git-operations-test.2
This was a version bump only for {project-name} to align it with other projects, there were no code changes.
## 999.9.9-changelog-git-operations-test.1
This was a version bump only for {project-name} to align it with other projects, there were no code changes.
`);
// Enable git commit and tag operations for the changelog command via config
updateJson('nx.json', (json) => {
return {
...json,
release: {
...json.release,
changelog: {
...json.release.changelog,
git: {
commit: true,
tag: true,
},
},
// Configure multiple release groups with different relationships to capture differences in commit body
groups: {
independent: {
projects: [pkg1, pkg2],
projectsRelationship: 'independent',
},
fixed: {
projects: [pkg3],
projectsRelationship: 'fixed',
},
},
},
};
});
const versionWithGitActionsConfigOutput = runCLI(
`release changelog 999.9.9-changelog-git-operations-test.3 --verbose` // add verbose so we get richer output
);
expect(versionWithGitActionsConfigOutput).toMatchInlineSnapshot(`
> NX Generating an entry in {project-name}/CHANGELOG.md for {project-name}@999.9.9-changelog-git-operations-test.3
+ ## 999.9.9-changelog-git-operations-test.3
+
+ This was a version bump only for {project-name} to align it with other projects, there were no code changes.
+
## 999.9.9-changelog-git-operations-test.2
This was a version bump only for {project-name} to align it with other projects, there were no code changes.
> NX Generating an entry in {project-name}/CHANGELOG.md for {project-name}@999.9.9-changelog-git-operations-test.3
+ ## 999.9.9-changelog-git-operations-test.3
+
+ This was a version bump only for {project-name} to align it with other projects, there were no code changes.
> NX Generating an entry in {project-name}/CHANGELOG.md for v999.9.9-changelog-git-operations-test.3
+ ## 999.9.9-changelog-git-operations-test.3
+
+ This was a version bump only for {project-name} to align it with other projects, there were no code changes.
> NX Committing changes with git
Staging files in git with the following command:
git add {project-name}/CHANGELOG.md {project-name}/CHANGELOG.md {project-name}/CHANGELOG.md
Committing files in git with the following command:
git commit --message chore(release): publish --message - project: {project-name} 999.9.9-changelog-git-operations-test.3 --message - project: {project-name} 999.9.9-changelog-git-operations-test.3 --message - release-group: fixed 999.9.9-changelog-git-operations-test.3
> NX Tagging commit with git
Tagging the current commit in git with the following command:
git tag --annotate {project-name}@999.9.9-changelog-git-operations-test.3 --message {project-name}@999.9.9-changelog-git-operations-test.3
Tagging the current commit in git with the following command:
git tag --annotate {project-name}@999.9.9-changelog-git-operations-test.3 --message {project-name}@999.9.9-changelog-git-operations-test.3
Tagging the current commit in git with the following command:
git tag --annotate v999.9.9-changelog-git-operations-test.3 --message v999.9.9-changelog-git-operations-test.3
`);
// Ensure the git operations were performed
expect(runCommand(`git rev-parse HEAD`).trim()).not.toEqual(headSHA);
// Commit
expect(runCommand(`git --no-pager log -1 --pretty=format:%B`).trim())
.toMatchInlineSnapshot(`
chore(release): publish
- project: {project-name} 999.9.9-changelog-git-operations-test.3
- project: {project-name} 999.9.9-changelog-git-operations-test.3
- release-group: fixed 999.9.9-changelog-git-operations-test.3
`);
// Tags
expect(runCommand('git tag --points-at HEAD')).toMatchInlineSnapshot(`
{project-name}@999.9.9-changelog-git-operations-test.3
{project-name}@999.9.9-changelog-git-operations-test.3
v999.9.9-changelog-git-operations-test.3
`);
expect(readFile(joinPathFragments(pkg1, 'CHANGELOG.md')))
.toMatchInlineSnapshot(`
## 999.9.9-changelog-git-operations-test.3
This was a version bump only for {project-name} to align it with other projects, there were no code changes.
## 999.9.9-changelog-git-operations-test.2
This was a version bump only for {project-name} to align it with other projects, there were no code changes.
## 999.9.9-changelog-git-operations-test.1
This was a version bump only for {project-name} to align it with other projects, there were no code changes.
`);
});
});
});
|
2,039 | 0 | petrpan-code/nrwl/nx/e2e/release | petrpan-code/nrwl/nx/e2e/release/src/private-js-packages.test.ts | import {
cleanupProject,
newProject,
runCLI,
tmpProjPath,
uniq,
updateJson,
} from '@nx/e2e/utils';
import { execSync } from 'child_process';
expect.addSnapshotSerializer({
serialize(str: string) {
return (
str
// Remove all output unique to specific projects to ensure deterministic snapshots
.replaceAll(`/private/${tmpProjPath()}`, '')
.replaceAll(tmpProjPath(), '')
.replaceAll('/private/', '')
.replaceAll(/public-pkg-\d+/g, '{public-project-name}')
.replaceAll(/private-pkg\d+/g, '{private-project-name}')
.replaceAll(/\s\/{private-project-name}/g, ' {private-project-name}')
.replaceAll(
/integrity:\s*.*/g,
'integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
)
.replaceAll(/\b[0-9a-f]{40}\b/g, '{SHASUM}')
.replaceAll(/\d*B index\.js/g, 'XXB index.js')
.replaceAll(/\d*B project\.json/g, 'XXB project.json')
.replaceAll(/\d*B package\.json/g, 'XXXB package.json')
.replaceAll(/size:\s*\d*\s?B/g, 'size: XXXB')
.replaceAll(/\d*\.\d*\s?kB/g, 'XXX.XXX kb')
// We trim each line to reduce the chances of snapshot flakiness
.split('\n')
.map((r) => r.trim())
.join('\n')
);
},
test(val: string) {
return val != null && typeof val === 'string';
},
});
describe('nx release - private JS packages', () => {
let publicPkg1: string;
let publicPkg2: string;
let privatePkg: string;
beforeAll(() => {
newProject({
unsetProjectNameAndRootFormat: false,
});
publicPkg1 = uniq('public-pkg-1');
runCLI(`generate @nx/workspace:npm-package ${publicPkg1}`);
publicPkg2 = uniq('public-pkg-2');
runCLI(`generate @nx/workspace:npm-package ${publicPkg2}`);
privatePkg = uniq('private-pkg');
runCLI(`generate @nx/workspace:npm-package ${privatePkg}`);
updateJson(`${privatePkg}/package.json`, (json) => {
json.private = true;
return json;
});
/**
* Update public-pkg2 to depend on private-pkg.
*
* At the time of writing this is not something we protect the user against,
* so we expect this to not cause any issues, and public-pkg2 will be published.
*
* TODO: these tests will need to be updated when we add support for protecting against this
*/
updateJson(`${publicPkg2}/package.json`, (json) => {
json.dependencies ??= {};
json.dependencies[`@proj/${privatePkg}`] = '0.0.0';
return json;
});
/**
* Configure independent releases in the most minimal way possible so that we can publish
* the projects independently.
*/
updateJson('nx.json', () => {
return {
release: {
projectsRelationship: 'independent',
},
};
});
});
afterAll(() => cleanupProject());
it('should skip private packages and log a warning', async () => {
runCLI(`release version 999.9.9`);
// This is the verdaccio instance that the e2e tests themselves are working from
const e2eRegistryUrl = execSync('npm config get registry')
.toString()
.trim();
// Thanks to the custom serializer above, the publish output should be deterministic
const publicPkg1PublishOutput = runCLI(`release publish -p ${publicPkg1}`);
expect(publicPkg1PublishOutput).toMatchInlineSnapshot(`
> NX Your filter "{public-project-name}" matched the following projects:
- {public-project-name}
> NX Running target nx-release-publish for project {public-project-name}:
- {public-project-name}
> nx run {public-project-name}:nx-release-publish
π¦ @proj/{public-project-name}@999.9.9
=== Tarball Contents ===
XXB index.js
XXXB package.json
XXB project.json
=== Tarball Details ===
name: @proj/{public-project-name}
version: 999.9.9
filename: proj-{public-project-name}-999.9.9.tgz
package size: XXXB
unpacked size: XXXB
shasum: {SHASUM}
integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
total files: 3
Published to ${e2eRegistryUrl} with tag "latest"
> NX Successfully ran target nx-release-publish for project {public-project-name}
`);
// This will include the private package publish output as it is a dependency
const publicPkg2PublishOutput = runCLI(`release publish -p ${publicPkg2}`);
expect(publicPkg2PublishOutput).toMatchInlineSnapshot(`
> NX Your filter "{public-project-name}" matched the following projects:
- {public-project-name}
> NX Running target nx-release-publish for project {public-project-name} and 1 task it depends on:
- {public-project-name}
> nx run {private-project-name}:nx-release-publish
Skipping package "@proj/{private-project-name}" from project "{private-project-name}", because it has \`"private": true\` in {private-project-name}/package.json
> nx run {public-project-name}:nx-release-publish
π¦ @proj/{public-project-name}@999.9.9
=== Tarball Contents ===
XXB index.js
XXXB package.json
XXB project.json
=== Tarball Details ===
name: @proj/{public-project-name}
version: 999.9.9
filename: proj-{public-project-name}-999.9.9.tgz
package size: XXXB
unpacked size: XXXB
shasum: {SHASUM}
integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
total files: 3
Published to ${e2eRegistryUrl} with tag "latest"
> NX Successfully ran target nx-release-publish for project {public-project-name} and 1 task it depends on
`);
// The two public packages should have been published
expect(
execSync(`npm view @proj/${publicPkg1} version`).toString().trim()
).toEqual('999.9.9');
expect(
execSync(`npm view @proj/${publicPkg2} version`).toString().trim()
).toEqual('999.9.9');
// The private package should have never been published
expect(() => execSync(`npm view @proj/${privatePkg} version`)).toThrowError(
/npm ERR! code E404/
);
}, 500000);
});
|
2,040 | 0 | petrpan-code/nrwl/nx/e2e/release | petrpan-code/nrwl/nx/e2e/release/src/release.test.ts | import { NxJsonConfiguration } from '@nx/devkit';
import {
cleanupProject,
createFile,
exists,
killProcessAndPorts,
newProject,
readFile,
runCLI,
runCommandAsync,
runCommandUntil,
uniq,
updateJson,
} from '@nx/e2e/utils';
import { execSync } from 'child_process';
expect.addSnapshotSerializer({
serialize(str: string) {
return (
str
// Remove all output unique to specific projects to ensure deterministic snapshots
.replaceAll(/my-pkg-\d+/g, '{project-name}')
.replaceAll(
/integrity:\s*.*/g,
'integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
)
.replaceAll(/\b[0-9a-f]{40}\b/g, '{SHASUM}')
.replaceAll(/\d*B index\.js/g, 'XXB index.js')
.replaceAll(/\d*B project\.json/g, 'XXB project.json')
.replaceAll(/\d*B package\.json/g, 'XXXB package.json')
.replaceAll(/size:\s*\d*\s?B/g, 'size: XXXB')
.replaceAll(/\d*\.\d*\s?kB/g, 'XXX.XXX kb')
.replaceAll(/[a-fA-F0-9]{7}/g, '{COMMIT_SHA}')
// We trim each line to reduce the chances of snapshot flakiness
.split('\n')
.map((r) => r.trim())
.join('\n')
);
},
test(val: string) {
return val != null && typeof val === 'string';
},
});
describe('nx release', () => {
let pkg1: string;
let pkg2: string;
let pkg3: string;
beforeAll(() => {
newProject({
unsetProjectNameAndRootFormat: false,
});
pkg1 = uniq('my-pkg-1');
runCLI(`generate @nx/workspace:npm-package ${pkg1}`);
pkg2 = uniq('my-pkg-2');
runCLI(`generate @nx/workspace:npm-package ${pkg2}`);
pkg3 = uniq('my-pkg-3');
runCLI(`generate @nx/workspace:npm-package ${pkg3}`);
// Update pkg2 to depend on pkg1
updateJson(`${pkg2}/package.json`, (json) => {
json.dependencies ??= {};
json.dependencies[`@proj/${pkg1}`] = '0.0.0';
return json;
});
});
afterAll(() => cleanupProject());
it('should version and publish multiple related npm packages with zero config', async () => {
// Normalize git committer information so it is deterministic in snapshots
await runCommandAsync(`git config user.email "[email protected]"`);
await runCommandAsync(`git config user.name "Test"`);
// Create a baseline version tag
await runCommandAsync(`git tag v0.0.0`);
// Add an example feature so that we can generate a CHANGELOG.md for it
createFile('an-awesome-new-thing.js', 'console.log("Hello world!");');
await runCommandAsync(
`git add --all && git commit -m "feat: an awesome new feature"`
);
const versionOutput = runCLI(`release version 999.9.9`);
/**
* We can't just assert on the whole version output as a snapshot because the order of the projects
* is non-deterministic, and not every project has the same number of log lines (because of the
* dependency relationship)
*/
expect(
versionOutput.match(/Running release version for project: my-pkg-\d*/g)
.length
).toEqual(3);
expect(
versionOutput.match(
/Reading data for package "@proj\/my-pkg-\d*" from my-pkg-\d*\/package.json/g
).length
).toEqual(3);
expect(
versionOutput.match(
/Resolved the current version as 0.0.0 from my-pkg-\d*\/package.json/g
).length
).toEqual(3);
expect(
versionOutput.match(
/New version 999.9.9 written to my-pkg-\d*\/package.json/g
).length
).toEqual(3);
// Only one dependency relationship exists, so this log should only match once
expect(
versionOutput.match(
/Applying new version 999.9.9 to 1 package which depends on my-pkg-\d*/g
).length
).toEqual(1);
// Generate a changelog for the new version
expect(exists('CHANGELOG.md')).toEqual(false);
const changelogOutput = runCLI(`release changelog 999.9.9`);
expect(changelogOutput).toMatchInlineSnapshot(`
> NX Generating an entry in CHANGELOG.md for v999.9.9
+ ## 999.9.9
+
+
+ ### π Features
+
+ - an awesome new feature
+
+ ### β€οΈ Thank You
+
+ - Test
`);
expect(readFile('CHANGELOG.md')).toMatchInlineSnapshot(`
## 999.9.9
### π Features
- an awesome new feature
### β€οΈ Thank You
- Test
`);
// This is the verdaccio instance that the e2e tests themselves are working from
const e2eRegistryUrl = execSync('npm config get registry')
.toString()
.trim();
// Thanks to the custom serializer above, the publish output should be deterministic
const publishOutput = runCLI(`release publish`);
expect(publishOutput).toMatchInlineSnapshot(`
> NX Running target nx-release-publish for 3 projects:
- {project-name}
- {project-name}
- {project-name}
> nx run {project-name}:nx-release-publish
π¦ @proj/{project-name}@999.9.9
=== Tarball Contents ===
XXB index.js
XXXB package.json
XXB project.json
=== Tarball Details ===
name: @proj/{project-name}
version: 999.9.9
filename: proj-{project-name}-999.9.9.tgz
package size: XXXB
unpacked size: XXXB
shasum: {SHASUM}
integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
total files: 3
Published to ${e2eRegistryUrl} with tag "latest"
> nx run {project-name}:nx-release-publish
π¦ @proj/{project-name}@999.9.9
=== Tarball Contents ===
XXB index.js
XXXB package.json
XXB project.json
=== Tarball Details ===
name: @proj/{project-name}
version: 999.9.9
filename: proj-{project-name}-999.9.9.tgz
package size: XXXB
unpacked size: XXXB
shasum: {SHASUM}
integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
total files: 3
Published to ${e2eRegistryUrl} with tag "latest"
> nx run {project-name}:nx-release-publish
π¦ @proj/{project-name}@999.9.9
=== Tarball Contents ===
XXB index.js
XXXB package.json
XXB project.json
=== Tarball Details ===
name: @proj/{project-name}
version: 999.9.9
filename: proj-{project-name}-999.9.9.tgz
package size: XXXB
unpacked size: XXXB
shasum: {SHASUM}
integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
total files: 3
Published to ${e2eRegistryUrl} with tag "latest"
> NX Successfully ran target nx-release-publish for 3 projects
`);
expect(
execSync(`npm view @proj/${pkg1} version`).toString().trim()
).toEqual('999.9.9');
expect(
execSync(`npm view @proj/${pkg2} version`).toString().trim()
).toEqual('999.9.9');
expect(
execSync(`npm view @proj/${pkg3} version`).toString().trim()
).toEqual('999.9.9');
// Add custom nx release config to control version resolution
updateJson<NxJsonConfiguration>('nx.json', (nxJson) => {
nxJson.release = {
groups: {
default: {
// @proj/source will be added as a project by the verdaccio setup, but we aren't versioning or publishing it, so we exclude it here
projects: ['*', '!@proj/source'],
version: {
generator: '@nx/js:release-version',
generatorOptions: {
// Resolve the latest version from the custom registry instance, therefore finding the previously published versions
currentVersionResolver: 'registry',
currentVersionResolverMetadata: {
registry: e2eRegistryUrl,
tag: 'latest',
},
},
},
},
},
};
return nxJson;
});
// Run additional custom verdaccio instance to publish the packages to
runCLI(`generate setup-verdaccio`);
const verdaccioPort = 7190;
const customRegistryUrl = `http://localhost:${verdaccioPort}`;
const process = await runCommandUntil(
`local-registry @proj/source --port=${verdaccioPort}`,
(output) => output.includes(`warn --- http address`)
);
const versionOutput2 = runCLI(`release version premajor --preid next`); // version using semver keyword this time (and custom preid)
expect(
versionOutput2.match(/Running release version for project: my-pkg-\d*/g)
.length
).toEqual(3);
expect(
versionOutput2.match(
/Reading data for package "@proj\/my-pkg-\d*" from my-pkg-\d*\/package.json/g
).length
).toEqual(3);
// It should resolve the current version from the registry once...
expect(
versionOutput2.match(
new RegExp(
`Resolved the current version as 999.9.9 for tag "latest" from registry ${e2eRegistryUrl}`,
'g'
)
).length
).toEqual(1);
// ...and then reuse it twice
expect(
versionOutput2.match(
new RegExp(
`Using the current version 999.9.9 already resolved from the registry ${e2eRegistryUrl}`,
'g'
)
).length
).toEqual(2);
expect(
versionOutput2.match(
/New version 1000.0.0-next.0 written to my-pkg-\d*\/package.json/g
).length
).toEqual(3);
// Only one dependency relationship exists, so this log should only match once
expect(
versionOutput2.match(
/Applying new version 1000.0.0-next.0 to 1 package which depends on my-pkg-\d*/g
).length
).toEqual(1);
// Perform an initial dry-run of the publish to the custom registry (not e2e registry), and a custom dist tag of "next"
const publishToNext = `release publish --registry=${customRegistryUrl} --tag=next`;
const publishOutput2 = runCLI(`${publishToNext} --dry-run`);
expect(publishOutput2).toMatchInlineSnapshot(`
> NX Running target nx-release-publish for 3 projects:
- {project-name}
- {project-name}
- {project-name}
With additional flags:
--registry=${customRegistryUrl}
--tag=next
--dryRun=true
> nx run {project-name}:nx-release-publish
π¦ @proj/{project-name}@1000.0.0-next.0
=== Tarball Contents ===
XXB index.js
XXXB package.json
XXB project.json
=== Tarball Details ===
name: @proj/{project-name}
version: 1000.0.0-next.0
filename: proj-{project-name}-1000.0.0-next.0.tgz
package size: XXXB
unpacked size: XXXB
shasum: {SHASUM}
integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
total files: 3
Would publish to ${customRegistryUrl} with tag "next", but [dry-run] was set
> nx run {project-name}:nx-release-publish
π¦ @proj/{project-name}@1000.0.0-next.0
=== Tarball Contents ===
XXB index.js
XXXB package.json
XXB project.json
=== Tarball Details ===
name: @proj/{project-name}
version: 1000.0.0-next.0
filename: proj-{project-name}-1000.0.0-next.0.tgz
package size: XXXB
unpacked size: XXXB
shasum: {SHASUM}
integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
total files: 3
Would publish to ${customRegistryUrl} with tag "next", but [dry-run] was set
> nx run {project-name}:nx-release-publish
π¦ @proj/{project-name}@1000.0.0-next.0
=== Tarball Contents ===
XXB index.js
XXXB package.json
XXB project.json
=== Tarball Details ===
name: @proj/{project-name}
version: 1000.0.0-next.0
filename: proj-{project-name}-1000.0.0-next.0.tgz
package size: XXXB
unpacked size: XXXB
shasum: {SHASUM}
integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
total files: 3
Would publish to ${customRegistryUrl} with tag "next", but [dry-run] was set
> NX Successfully ran target nx-release-publish for 3 projects
`);
// Versions are still unpublished on the next tag in the custom registry, because it was only a dry-run
expect(() =>
execSync(
`npm view @proj/${pkg1}@next version --registry=${customRegistryUrl}`
)
).toThrowError(/npm ERR! code E404/);
expect(() =>
execSync(
`npm view @proj/${pkg2}@next version --registry=${customRegistryUrl}`
)
).toThrowError(/npm ERR! code E404/);
expect(() =>
execSync(
`npm view @proj/${pkg3}@next version --registry=${customRegistryUrl}`
)
).toThrowError(/npm ERR! code E404/);
// Actually publish to the custom registry (not e2e registry), and a custom dist tag of "next"
const publishOutput3 = runCLI(publishToNext);
expect(publishOutput3).toMatchInlineSnapshot(`
> NX Running target nx-release-publish for 3 projects:
- {project-name}
- {project-name}
- {project-name}
With additional flags:
--registry=${customRegistryUrl}
--tag=next
> nx run {project-name}:nx-release-publish
π¦ @proj/{project-name}@1000.0.0-next.0
=== Tarball Contents ===
XXB index.js
XXXB package.json
XXB project.json
=== Tarball Details ===
name: @proj/{project-name}
version: 1000.0.0-next.0
filename: proj-{project-name}-1000.0.0-next.0.tgz
package size: XXXB
unpacked size: XXXB
shasum: {SHASUM}
integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
total files: 3
Published to ${customRegistryUrl} with tag "next"
> nx run {project-name}:nx-release-publish
π¦ @proj/{project-name}@1000.0.0-next.0
=== Tarball Contents ===
XXB index.js
XXXB package.json
XXB project.json
=== Tarball Details ===
name: @proj/{project-name}
version: 1000.0.0-next.0
filename: proj-{project-name}-1000.0.0-next.0.tgz
package size: XXXB
unpacked size: XXXB
shasum: {SHASUM}
integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
total files: 3
Published to ${customRegistryUrl} with tag "next"
> nx run {project-name}:nx-release-publish
π¦ @proj/{project-name}@1000.0.0-next.0
=== Tarball Contents ===
XXB index.js
XXXB package.json
XXB project.json
=== Tarball Details ===
name: @proj/{project-name}
version: 1000.0.0-next.0
filename: proj-{project-name}-1000.0.0-next.0.tgz
package size: XXXB
unpacked size: XXXB
shasum: {SHASUM}
integrity: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
total files: 3
Published to ${customRegistryUrl} with tag "next"
> NX Successfully ran target nx-release-publish for 3 projects
`);
// The versions now exist on the next tag in the custom registry
expect(
execSync(
`npm view @proj/${pkg1}@next version --registry=${customRegistryUrl}`
)
.toString()
.trim()
).toEqual('1000.0.0-next.0');
expect(
execSync(
`npm view @proj/${pkg2}@next version --registry=${customRegistryUrl}`
)
.toString()
.trim()
).toEqual('1000.0.0-next.0');
expect(
execSync(
`npm view @proj/${pkg3}@next version --registry=${customRegistryUrl}`
)
.toString()
.trim()
).toEqual('1000.0.0-next.0');
// Update custom nx release config to demonstrate project level changelogs
updateJson<NxJsonConfiguration>('nx.json', (nxJson) => {
nxJson.release = {
groups: {
default: {
// @proj/source will be added as a project by the verdaccio setup, but we aren't versioning or publishing it, so we exclude it here
projects: ['*', '!@proj/source'],
changelog: {
// This should be merged with and take priority over the projectChangelogs config at the root of the config
createRelease: 'github',
},
},
},
changelog: {
projectChangelogs: {
renderOptions: {
createRelease: false, // will be overridden by the group
// Customize the changelog renderer to not print the Thank You section this time (not overridden by the group)
includeAuthors: false,
},
},
},
};
return nxJson;
});
// We need a valid git origin for the command to work when createRelease is set
await runCommandAsync(
`git remote add origin https://github.com/nrwl/fake-repo.git`
);
// Perform a dry-run this time to show that it works but also prevent making any requests to github within the test
const changelogDryRunOutput = runCLI(
`release changelog 1000.0.0-next.0 --dry-run`
);
expect(changelogDryRunOutput).toMatchInlineSnapshot(`
> NX Previewing an entry in CHANGELOG.md for v1000.0.0-next.0
+ ## 1000.0.0-next.0
+
+
+ ### π Features
+
+ - an awesome new feature
+
+ ### β€οΈ Thank You
+
+ - Test
+
## 999.9.9
> NX Previewing a Github release and an entry in {project-name}/CHANGELOG.md for v1000.0.0-next.0
+ ## 1000.0.0-next.0
+
+
+ ### π Features
+
+ - an awesome new feature ([{COMMIT_SHA}](https://github.com/nrwl/fake-repo/commit/{COMMIT_SHA}))
> NX Previewing a Github release and an entry in {project-name}/CHANGELOG.md for v1000.0.0-next.0
+ ## 1000.0.0-next.0
+
+
+ ### π Features
+
+ - an awesome new feature ([{COMMIT_SHA}](https://github.com/nrwl/fake-repo/commit/{COMMIT_SHA}))
> NX Previewing a Github release and an entry in {project-name}/CHANGELOG.md for v1000.0.0-next.0
+ ## 1000.0.0-next.0
+
+
+ ### π Features
+
+ - an awesome new feature ([{COMMIT_SHA}](https://github.com/nrwl/fake-repo/commit/{COMMIT_SHA}))
`);
// port and process cleanup
await killProcessAndPorts(process.pid, verdaccioPort);
// Add custom nx release config to control version resolution
updateJson<NxJsonConfiguration>('nx.json', (nxJson) => {
nxJson.release = {
groups: {
default: {
// @proj/source will be added as a project by the verdaccio setup, but we aren't versioning or publishing it, so we exclude it here
projects: ['*', '!@proj/source'],
releaseTagPattern: 'xx{version}',
version: {
generator: '@nx/js:release-version',
generatorOptions: {
// Resolve the latest version from the git tag
currentVersionResolver: 'git-tag',
},
},
},
},
};
return nxJson;
});
// Add a git tag to the repo
await runCommandAsync(`git tag xx1100.0.0`);
const versionOutput3 = runCLI(`release version minor`);
expect(
versionOutput3.match(/Running release version for project: my-pkg-\d*/g)
.length
).toEqual(3);
expect(
versionOutput3.match(
/Reading data for package "@proj\/my-pkg-\d*" from my-pkg-\d*\/package.json/g
).length
).toEqual(3);
// It should resolve the current version from the git tag once...
expect(
versionOutput3.match(
new RegExp(
`Resolved the current version as 1100.0.0 from git tag "xx1100.0.0"`,
'g'
)
).length
).toEqual(1);
// ...and then reuse it twice
expect(
versionOutput3.match(
new RegExp(
`Using the current version 1100.0.0 already resolved from git tag "xx1100.0.0"`,
'g'
)
).length
).toEqual(2);
expect(
versionOutput3.match(
/New version 1100.1.0 written to my-pkg-\d*\/package.json/g
).length
).toEqual(3);
// Only one dependency relationship exists, so this log should only match once
expect(
versionOutput3.match(
/Applying new version 1100.1.0 to 1 package which depends on my-pkg-\d*/g
).length
).toEqual(1);
createFile(
`${pkg1}/my-file.txt`,
'update for conventional-commits testing'
);
// Add custom nx release config to control version resolution
updateJson<NxJsonConfiguration>('nx.json', (nxJson) => {
nxJson.release = {
groups: {
default: {
// @proj/source will be added as a project by the verdaccio setup, but we aren't versioning or publishing it, so we exclude it here
projects: ['*', '!@proj/source'],
releaseTagPattern: 'xx{version}',
version: {
generator: '@nx/js:release-version',
generatorOptions: {
specifierSource: 'conventional-commits',
currentVersionResolver: 'git-tag',
},
},
},
},
};
return nxJson;
});
const versionOutput4 = runCLI(`release version`);
expect(
versionOutput4.match(/Running release version for project: my-pkg-\d*/g)
.length
).toEqual(3);
expect(
versionOutput4.match(
/Reading data for package "@proj\/my-pkg-\d*" from my-pkg-\d*\/package.json/g
).length
).toEqual(3);
// It should resolve the current version from the git tag once...
expect(
versionOutput4.match(
new RegExp(
`Resolved the current version as 1100.0.0 from git tag "xx1100.0.0"`,
'g'
)
).length
).toEqual(1);
// ...and then reuse it twice
expect(
versionOutput4.match(
new RegExp(
`Using the current version 1100.0.0 already resolved from git tag "xx1100.0.0"`,
'g'
)
).length
).toEqual(2);
expect(versionOutput4.match(/Skipping versioning/g).length).toEqual(3);
await runCommandAsync(
`git add ${pkg1}/my-file.txt && git commit -m "feat!: add new file"`
);
const versionOutput5 = runCLI(`release version`);
expect(
versionOutput5.match(
/New version 1101.0.0 written to my-pkg-\d*\/package.json/g
).length
).toEqual(3);
}, 500000);
});
|
2,045 | 0 | petrpan-code/nrwl/nx/e2e/rollup | petrpan-code/nrwl/nx/e2e/rollup/src/rollup.test.ts | import {
checkFilesExist,
cleanupProject,
newProject,
readJson,
rmDist,
runCLI,
runCommand,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('Rollup Plugin', () => {
beforeAll(() => newProject());
afterAll(() => cleanupProject());
it('should be able to setup project to build node programs with rollup and different compilers', async () => {
const myPkg = uniq('my-pkg');
runCLI(`generate @nx/js:lib ${myPkg} --bundler=none`);
updateFile(`libs/${myPkg}/src/index.ts`, `console.log('Hello');\n`);
// babel (default)
runCLI(
`generate @nx/rollup:configuration ${myPkg} --target=node --tsConfig=libs/${myPkg}/tsconfig.lib.json --main=libs/${myPkg}/src/index.ts`
);
rmDist();
runCLI(`build ${myPkg} --format=cjs,esm --generateExportsField`);
checkFilesExist(`dist/libs/${myPkg}/index.cjs.d.ts`);
expect(readJson(`dist/libs/${myPkg}/package.json`).exports).toEqual({
'.': {
module: './index.esm.js',
import: './index.cjs.mjs',
default: './index.cjs.js',
},
'./package.json': './package.json',
});
let output = runCommand(`node dist/libs/${myPkg}/index.cjs.js`);
expect(output).toMatch(/Hello/);
updateJson(join('libs', myPkg, 'project.json'), (config) => {
delete config.targets.build;
return config;
});
// swc
runCLI(
`generate @nx/rollup:configuration ${myPkg} --target=node --tsConfig=libs/${myPkg}/tsconfig.lib.json --main=libs/${myPkg}/src/index.ts --compiler=swc`
);
rmDist();
runCLI(`build ${myPkg} --format=cjs,esm --generateExportsField`);
output = runCommand(`node dist/libs/${myPkg}/index.cjs.js`);
expect(output).toMatch(/Hello/);
updateJson(join('libs', myPkg, 'project.json'), (config) => {
delete config.targets.build;
return config;
});
// tsc
runCLI(
`generate @nx/rollup:configuration ${myPkg} --target=node --tsConfig=libs/${myPkg}/tsconfig.lib.json --main=libs/${myPkg}/src/index.ts --compiler=tsc`
);
rmDist();
runCLI(`build ${myPkg} --format=cjs,esm --generateExportsField`);
output = runCommand(`node dist/libs/${myPkg}/index.cjs.js`);
expect(output).toMatch(/Hello/);
}, 500000);
it('should support additional entry-points', async () => {
const myPkg = uniq('my-pkg');
runCLI(`generate @nx/js:lib ${myPkg} --bundler=none`);
runCLI(
`generate @nx/rollup:configuration ${myPkg} --target=node --tsConfig=libs/${myPkg}/tsconfig.lib.json --main=libs/${myPkg}/src/index.ts --compiler=tsc`
);
updateJson(join('libs', myPkg, 'project.json'), (config) => {
config.targets.build.options.format = ['cjs', 'esm'];
config.targets.build.options.generateExportsField = true;
config.targets.build.options.additionalEntryPoints = [
`libs/${myPkg}/src/{foo,bar}.ts`,
];
return config;
});
updateFile(`libs/${myPkg}/src/foo.ts`, `export const foo = 'foo';`);
updateFile(`libs/${myPkg}/src/bar.ts`, `export const bar = 'bar';`);
runCLI(`build ${myPkg}`);
checkFilesExist(`dist/libs/${myPkg}/index.esm.js`);
checkFilesExist(`dist/libs/${myPkg}/index.cjs.js`);
checkFilesExist(`dist/libs/${myPkg}/index.cjs.d.ts`);
checkFilesExist(`dist/libs/${myPkg}/foo.esm.js`);
checkFilesExist(`dist/libs/${myPkg}/foo.cjs.js`);
checkFilesExist(`dist/libs/${myPkg}/bar.esm.js`);
checkFilesExist(`dist/libs/${myPkg}/bar.cjs.js`);
expect(readJson(`dist/libs/${myPkg}/package.json`).exports).toEqual({
'./package.json': './package.json',
'.': {
module: './index.esm.js',
import: './index.cjs.mjs',
default: './index.cjs.js',
},
'./bar': {
module: './bar.esm.js',
import: './bar.cjs.mjs',
default: './bar.cjs.js',
},
'./foo': {
module: './foo.esm.js',
import: './foo.cjs.mjs',
default: './foo.cjs.js',
},
});
});
it('should be able to build libs generated with @nx/js:lib --bundler rollup', () => {
const jsLib = uniq('jslib');
runCLI(`generate @nx/js:lib ${jsLib} --bundler rollup`);
expect(() => runCLI(`build ${jsLib}`)).not.toThrow();
});
});
|
2,050 | 0 | petrpan-code/nrwl/nx/e2e/storybook-angular | petrpan-code/nrwl/nx/e2e/storybook-angular/src/storybook-angular.test.ts | import {
checkFilesExist,
cleanupProject,
killPorts,
newProject,
runCLI,
runCommandUntil,
uniq,
} from '@nx/e2e/utils';
describe('Storybook executors for Angular', () => {
const angularStorybookLib = uniq('test-ui-ng-lib');
beforeAll(() => {
newProject();
runCLI(
`g @nx/angular:library ${angularStorybookLib} --project-name-and-root-format=as-provided --no-interactive`
);
runCLI(
`generate @nx/angular:storybook-configuration ${angularStorybookLib} --generateStories --no-interactive`
);
});
afterAll(() => {
cleanupProject();
});
describe('serve and build storybook', () => {
afterAll(() => killPorts());
it('should serve an Angular based Storybook setup', async () => {
const p = await runCommandUntil(
`run ${angularStorybookLib}:storybook`,
(output) => {
return /Storybook.*started/gi.test(output);
}
);
p.kill();
}, 200_000);
// Increased timeout because 92% sealing asset processing TerserPlugin
// TODO(meeroslav) this test is still flaky and breaks the PR runs. We need to investigate why.
xit('shoud build an Angular based storybook', () => {
runCLI(`run ${angularStorybookLib}:build-storybook`);
checkFilesExist(`dist/storybook/${angularStorybookLib}/index.html`);
}, 1_000_000);
});
});
|
2,055 | 0 | petrpan-code/nrwl/nx/e2e/storybook | petrpan-code/nrwl/nx/e2e/storybook/src/storybook-nested.test.ts | import {
checkFilesExist,
cleanupProject,
getSelectedPackageManager,
killPorts,
readJson,
runCLI,
runCommandUntil,
runCreateWorkspace,
tmpProjPath,
uniq,
} from '@nx/e2e/utils';
import { writeFileSync } from 'fs';
import { createFileSync } from 'fs-extra';
describe('Storybook generators and executors for standalone workspaces - using React + Vite', () => {
const appName = uniq('react');
beforeAll(() => {
// create a workspace with a single react app at the root
runCreateWorkspace(appName, {
preset: 'react-standalone',
appName,
style: 'css',
bundler: 'vite',
packageManager: getSelectedPackageManager(),
e2eTestRunner: 'none',
});
runCLI(
`generate @nx/react:storybook-configuration ${appName} --generateStories --no-interactive`
);
runCLI(`report`);
});
afterAll(() => {
cleanupProject();
});
describe('Storybook generated files', () => {
it('should generate storybook files', () => {
checkFilesExist(
'.storybook/main.ts',
'.storybook/preview.ts',
'tsconfig.storybook.json'
);
});
it('should edit root tsconfig.json', () => {
const tsconfig = readJson(`tsconfig.json`);
expect(tsconfig['ts-node']?.compilerOptions?.module).toEqual('commonjs');
});
});
describe('serve storybook', () => {
afterEach(() => killPorts());
it('should serve a React based Storybook setup that uses Vite', async () => {
const p = await runCommandUntil(`run ${appName}:storybook`, (output) => {
return /Storybook.*started/gi.test(output);
});
p.kill();
}, 100_000);
});
describe('build storybook', () => {
it('should build a React based storybook that uses Vite', () => {
runCLI(`run ${appName}:build-storybook --verbose`);
checkFilesExist(`dist/storybook/${appName}/index.html`);
}, 100_000);
it('should build a React based storybook that references another lib and uses Vite', () => {
runCLI(
`generate @nx/react:lib my-lib --bundler=vite --unitTestRunner=none --project-name-and-root-format=as-provided --no-interactive`
);
// create a component and a story in the first lib to reference the cmp from the 2nd lib
createFileSync(tmpProjPath(`src/app/test-button.tsx`));
writeFileSync(
tmpProjPath(`src/app/test-button.tsx`),
`
import { MyLib } from '@${appName}/my-lib';
export function TestButton() {
return (
<div>
<MyLib />
</div>
);
}
export default TestButton;
`
);
// create a story in the first lib to reference the cmp from the 2nd lib
createFileSync(tmpProjPath(`src/app/test-button.stories.tsx`));
writeFileSync(
tmpProjPath(`src/app/test-button.stories.tsx`),
`
import type { Meta } from '@storybook/react';
import { TestButton } from './test-button';
const Story: Meta<typeof TestButton> = {
component: TestButton,
title: 'TestButton',
};
export default Story;
export const Primary = {
args: {},
};
`
);
// build React lib
runCLI(`run ${appName}:build-storybook --verbose`);
checkFilesExist(`dist/storybook/${appName}/index.html`);
}, 150_000);
});
});
|
2,056 | 0 | petrpan-code/nrwl/nx/e2e/storybook | petrpan-code/nrwl/nx/e2e/storybook/src/storybook.test.ts | import {
checkFilesExist,
cleanupProject,
killPorts,
newProject,
runCLI,
runCommandUntil,
setMaxWorkers,
tmpProjPath,
uniq,
} from '@nx/e2e/utils';
import { writeFileSync } from 'fs';
import { createFileSync } from 'fs-extra';
import { join } from 'path';
describe('Storybook generators and executors for monorepos', () => {
const reactStorybookApp = uniq('react-app');
let proj;
beforeAll(async () => {
proj = newProject();
runCLI(
`generate @nx/react:app ${reactStorybookApp} --bundler=webpack --project-name-and-root-format=as-provided --no-interactive`
);
setMaxWorkers(join(reactStorybookApp, 'project.json'));
runCLI(
`generate @nx/react:storybook-configuration ${reactStorybookApp} --generateStories --no-interactive --bundler=webpack`
);
});
afterAll(() => {
cleanupProject();
});
// TODO: enable this when Storybook webpack server becomes a bit faster
xdescribe('serve storybook', () => {
afterEach(() => killPorts());
it('should serve a React based Storybook setup that uses Vite', async () => {
const p = await runCommandUntil(
`run ${reactStorybookApp}:storybook`,
(output) => {
return /Storybook.*started/gi.test(output);
}
);
p.kill();
}, 600_000);
});
describe('build storybook', () => {
it('should build a React based storybook setup that uses webpack', () => {
// build
runCLI(`run ${reactStorybookApp}:build-storybook --verbose`);
checkFilesExist(`dist/storybook/${reactStorybookApp}/index.html`);
}, 300_000);
// This test makes sure path resolution works
it('should build a React based storybook that references another lib and uses rollup', () => {
runCLI(
`generate @nx/react:lib my-lib --bundler=rollup --unitTestRunner=none --project-name-and-root-format=as-provided --no-interactive`
);
// create a component in the first lib to reference the cmp from the 2nd lib
createFileSync(
tmpProjPath(`${reactStorybookApp}/src/app/test-button.tsx`)
);
writeFileSync(
tmpProjPath(`${reactStorybookApp}/src/app/test-button.tsx`),
`
import { MyLib } from '@${proj}/my-lib';
export function TestButton() {
return (
<div>
<MyLib />
</div>
);
}
export default TestButton;
`
);
// create a story in the first lib to reference the cmp from the 2nd lib
createFileSync(
tmpProjPath(`${reactStorybookApp}/src/app/test-button.stories.tsx`)
);
writeFileSync(
tmpProjPath(`${reactStorybookApp}/src/app/test-button.stories.tsx`),
`
import type { Meta } from '@storybook/react';
import { TestButton } from './test-button';
const Story: Meta<typeof TestButton> = {
component: TestButton,
title: 'TestButton',
};
export default Story;
export const Primary = {
args: {},
};
`
);
// build React lib
runCLI(`run ${reactStorybookApp}:build-storybook --verbose`);
checkFilesExist(`dist/storybook/${reactStorybookApp}/index.html`);
}, 300_000);
});
});
|
2,072 | 0 | petrpan-code/nrwl/nx/e2e/vite | petrpan-code/nrwl/nx/e2e/vite/src/vite-esm.test.ts | import {
checkFilesExist,
newProject,
renameFile,
runCLI,
uniq,
updateJson,
} from '@nx/e2e/utils';
// TODO(jack): This test file can be removed when Vite goes ESM-only.
// This test ensures that when CJS is gone from the published `vite` package, Nx will continue to work.
describe('Vite ESM tests', () => {
beforeAll(() => newProject({ unsetProjectNameAndRootFormat: false }));
it('should build with Vite when it is ESM-only', async () => {
const appName = uniq('viteapp');
runCLI(`generate @nx/react:app ${appName} --bundler=vite`);
// .mts file is needed because Nx will transpile .ts files as CJS
renameFile(`${appName}/vite.config.ts`, `${appName}/vite.config.mts`);
// Remove CJS entry point for Vite
updateJson('node_modules/vite/package.json', (json) => {
for (const [key, value] of Object.entries(json.exports['.'])) {
if (typeof value === 'string' && value.endsWith('.cjs')) {
delete json.exports['.'][key];
}
}
return json;
});
runCLI(`build ${appName}`);
checkFilesExist(`dist/${appName}/index.html`);
});
});
|
2,073 | 0 | petrpan-code/nrwl/nx/e2e/vite | petrpan-code/nrwl/nx/e2e/vite/src/vite.test.ts | import { names } from '@nx/devkit';
import {
cleanupProject,
createFile,
directoryExists,
exists,
fileExists,
getPackageManagerCommand,
killPorts,
listFiles,
newProject,
promisifiedTreeKill,
readFile,
readJson,
removeFile,
rmDist,
runCLI,
runCommand,
runCLIAsync,
runCommandUntil,
tmpProjPath,
uniq,
updateFile,
updateJson,
checkFilesExist,
} from '@nx/e2e/utils';
import { join } from 'path';
const myApp = uniq('my-app');
describe('Vite Plugin', () => {
let proj: string;
describe('Vite on React apps', () => {
describe('convert React webpack app to vite using the vite:configuration generator', () => {
beforeEach(() => {
proj = newProject();
runCLI(`generate @nx/react:app ${myApp} --bundler=webpack`);
runCLI(`generate @nx/vite:configuration ${myApp}`);
});
afterEach(() => cleanupProject());
it('should serve application in dev mode with custom options', async () => {
const port = 4212;
const p = await runCommandUntil(
`run ${myApp}:serve --port=${port} --https=true`,
(output) => {
return (
output.includes('Local:') &&
output.includes(`:${port}`) &&
output.includes('https')
);
}
);
try {
await promisifiedTreeKill(p.pid, 'SIGKILL');
await killPorts(port);
} catch (e) {
// ignore
}
}, 200_000);
it('should test application', async () => {
const result = await runCLIAsync(`test ${myApp}`);
expect(result.combinedOutput).toContain(
`Successfully ran target test for project ${myApp}`
);
});
});
describe('set up new React app with --bundler=vite option', () => {
beforeEach(async () => {
proj = newProject();
runCLI(`generate @nx/react:app ${myApp} --bundler=vite`);
createFile(`apps/${myApp}/public/hello.md`, `# Hello World`);
updateFile(
`apps/${myApp}/src/environments/environment.prod.ts`,
`export const environment = {
production: true,
myTestVar: 'MyProductionValue',
};`
);
updateFile(
`apps/${myApp}/src/environments/environment.ts`,
`export const environment = {
production: false,
myTestVar: 'MyDevelopmentValue',
};`
);
updateFile(
`apps/${myApp}/src/app/app.tsx`,
`
import { environment } from './../environments/environment';
export function App() {
return (
<>
<h1>{environment.myTestVar}</h1>
<p>Welcome ${myApp}!</p>
</>
);
}
export default App;
`
);
updateJson(join('apps', myApp, 'project.json'), (config) => {
config.targets.build.options.fileReplacements = [
{
replace: `apps/${myApp}/src/environments/environment.ts`,
with: `apps/${myApp}/src/environments/environment.prod.ts`,
},
];
return config;
});
});
afterEach(() => cleanupProject());
it('should build application', async () => {
runCLI(`build ${myApp}`);
expect(readFile(`dist/apps/${myApp}/favicon.ico`)).toBeDefined();
expect(readFile(`dist/apps/${myApp}/hello.md`)).toBeDefined();
expect(readFile(`dist/apps/${myApp}/index.html`)).toBeDefined();
const fileArray = listFiles(`dist/apps/${myApp}/assets`);
const mainBundle = fileArray.find((file) => file.endsWith('.js'));
expect(readFile(`dist/apps/${myApp}/assets/${mainBundle}`)).toContain(
'MyProductionValue'
);
expect(
readFile(`dist/apps/${myApp}/assets/${mainBundle}`)
).not.toContain('MyDevelopmentValue');
rmDist();
}, 200_000);
});
});
describe('Vite on Web apps', () => {
describe('set up new @nx/web app with --bundler=vite option', () => {
beforeEach(() => {
proj = newProject();
runCLI(`generate @nx/web:app ${myApp} --bundler=vite`);
});
afterEach(() => cleanupProject());
it('should build application', async () => {
runCLI(`build ${myApp}`);
expect(readFile(`dist/apps/${myApp}/index.html`)).toBeDefined();
const fileArray = listFiles(`dist/apps/${myApp}/assets`);
const mainBundle = fileArray.find((file) => file.endsWith('.js'));
expect(
readFile(`dist/apps/${myApp}/assets/${mainBundle}`)
).toBeDefined();
expect(fileExists(`dist/apps/${myApp}/package.json`)).toBeFalsy();
rmDist();
}, 200_000);
it('should build application with new package json generation', async () => {
runCLI(`build ${myApp} --generatePackageJson`);
expect(readFile(`dist/apps/${myApp}/index.html`)).toBeDefined();
const fileArray = listFiles(`dist/apps/${myApp}/assets`);
const mainBundle = fileArray.find((file) => file.endsWith('.js'));
expect(
readFile(`dist/apps/${myApp}/assets/${mainBundle}`)
).toBeDefined();
const packageJson = readJson(`dist/apps/${myApp}/package.json`);
expect(packageJson).toEqual({
name: myApp,
version: '0.0.1',
type: 'module',
});
rmDist();
}, 200_000);
it('should build application with existing package json generation', async () => {
createFile(
`apps/${myApp}/package.json`,
JSON.stringify({
name: 'my-existing-app',
version: '1.0.1',
scripts: {
start: 'node server.js',
},
})
);
runCLI(`build ${myApp} --generatePackageJson`);
expect(readFile(`dist/apps/${myApp}/index.html`)).toBeDefined();
const fileArray = listFiles(`dist/apps/${myApp}/assets`);
const mainBundle = fileArray.find((file) => file.endsWith('.js'));
expect(
readFile(`dist/apps/${myApp}/assets/${mainBundle}`)
).toBeDefined();
const packageJson = readJson(`dist/apps/${myApp}/package.json`);
expect(packageJson).toEqual({
name: 'my-existing-app',
version: '1.0.1',
type: 'module',
scripts: {
start: 'node server.js',
},
});
rmDist();
}, 200_000);
});
describe('convert @nx/web webpack app to vite using the vite:configuration generator', () => {
beforeEach(() => {
proj = newProject();
runCLI(`generate @nx/web:app ${myApp} --bundler=webpack`);
runCLI(`generate @nx/vite:configuration ${myApp}`);
});
afterEach(() => cleanupProject());
it('should build application', async () => {
runCLI(`build ${myApp}`);
expect(readFile(`dist/apps/${myApp}/index.html`)).toBeDefined();
const fileArray = listFiles(`dist/apps/${myApp}/assets`);
const mainBundle = fileArray.find((file) => file.endsWith('.js'));
expect(
readFile(`dist/apps/${myApp}/assets/${mainBundle}`)
).toBeDefined();
rmDist();
}, 200_000);
it('should serve application in dev mode with custom port', async () => {
const port = 4212;
const p = await runCommandUntil(
`run ${myApp}:serve --port=${port}`,
(output) => {
return output.includes('Local:') && output.includes(`:${port}`);
}
);
try {
await promisifiedTreeKill(p.pid, 'SIGKILL');
await killPorts(port);
} catch {
// ignore
}
}, 200_000);
it('should test application', async () => {
const result = await runCLIAsync(`test ${myApp}`);
expect(result.combinedOutput).toContain(
`Successfully ran target test for project ${myApp}`
);
});
}),
100_000;
});
describe('incremental building', () => {
const app = uniq('demo');
const lib = uniq('my-lib');
beforeAll(() => {
proj = newProject({ name: uniq('vite-incr-build') });
runCLI(`generate @nx/react:app ${app} --bundler=vite --no-interactive`);
// only this project will be directly used from dist
runCLI(
`generate @nx/react:lib ${lib}-buildable --unitTestRunner=none --bundler=vite --importPath="@acme/buildable" --no-interactive`
);
runCLI(
`generate @nx/react:lib ${lib} --unitTestRunner=none --bundler=none --importPath="@acme/non-buildable" --no-interactive`
);
// because the default js lib builds as cjs it cannot be loaded from dist
// so the paths plugin should always resolve to the libs source
runCLI(
`generate @nx/js:lib ${lib}-js --bundler=tsc --importPath="@acme/js-lib" --no-interactive`
);
const buildableLibCmp = names(`${lib}-buildable`).className;
const nonBuildableLibCmp = names(lib).className;
const buildableJsLibFn = names(`${lib}-js`).propertyName;
updateFile(`apps/${app}/src/app/app.tsx`, () => {
return `
import styles from './app.module.css';
import NxWelcome from './nx-welcome';
import { ${buildableLibCmp} } from '@acme/buildable';
import { ${buildableJsLibFn} } from '@acme/js-lib';
import { ${nonBuildableLibCmp} } from '@acme/non-buildable';
export function App() {
return (
<div>
<${buildableLibCmp} />
<${nonBuildableLibCmp} />
<p>{${buildableJsLibFn}()}</p>
<NxWelcome title='${app}' />
</div>
);
}
export default App;
`;
});
});
afterAll(() => {
cleanupProject();
});
it('should build app from libs source', () => {
const results = runCLI(`build ${app} --buildLibsFromSource=true`);
expect(results).toContain('Successfully ran target build for project');
// this should be more modules than build from dist
expect(results).toContain('40 modules transformed');
});
it('should build app from libs dist', () => {
const results = runCLI(`build ${app} --buildLibsFromSource=false`);
expect(results).toContain('Successfully ran target build for project');
// this should be less modules than building from source
expect(results).toContain('38 modules transformed');
});
it('should build app from libs without package.json in lib', () => {
removeFile(`libs/${lib}-buildable/package.json`);
const buildFromSourceResults = runCLI(
`build ${app} --buildLibsFromSource=true`
);
expect(buildFromSourceResults).toContain(
'Successfully ran target build for project'
);
const noBuildFromSourceResults = runCLI(
`build ${app} --buildLibsFromSource=false`
);
expect(noBuildFromSourceResults).toContain(
'Successfully ran target build for project'
);
});
});
describe('should be able to create libs that use vitest', () => {
const lib = uniq('my-lib');
beforeEach(() => {
proj = newProject({ name: uniq('vite-proj') });
});
it('should be able to run tests', async () => {
runCLI(`generate @nx/react:lib ${lib} --unitTestRunner=vitest`);
expect(exists(tmpProjPath(`libs/${lib}/vite.config.ts`))).toBeTruthy();
const result = await runCLIAsync(`test ${lib}`);
expect(result.combinedOutput).toContain(
`Successfully ran target test for project ${lib}`
);
const nestedResults = await runCLIAsync(`test ${lib} --skip-nx-cache`, {
cwd: `${tmpProjPath()}/libs/${lib}`,
});
expect(nestedResults.combinedOutput).toContain(
`Successfully ran target test for project ${lib}`
);
}, 100_000);
it('should collect coverage', () => {
runCLI(`generate @nx/react:lib ${lib} --unitTestRunner=vitest`);
updateFile(`libs/${lib}/vite.config.ts`, () => {
return `/// <reference types='vitest' />
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
export default defineConfig({
server: {
port: 4200,
host: 'localhost',
},
plugins: [
react(),
nxViteTsPaths()
],
test: {
globals: true,
cache: {
dir: './node_modules/.vitest',
},
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
coverage: {
provider: "v8",
enabled: true,
lines: 100,
statements: 100,
functions: 100,
branches: 1000,
}
},
});
`;
});
const coverageDir = `${tmpProjPath()}/coverage/libs/${lib}`;
const results = runCLI(`test ${lib} --coverage`, { silenceError: true });
expect(results).toContain(
`Running target test for project ${lib} failed`
);
expect(results).toContain(`ERROR: Coverage`);
expect(directoryExists(coverageDir)).toBeTruthy();
}, 100_000);
// TODO: This takes forever and times out everything - find out why
xit('should not delete the project directory when coverage is enabled', async () => {
// when coverage is enabled in the vite.config.ts but reportsDirectory is removed
// from the @nx/vite:test executor options, vite will delete the project root directory
runCLI(`generate @nx/react:lib ${lib} --unitTestRunner=vitest`);
updateFile(`libs/${lib}/vite.config.ts`, () => {
return `import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
export default defineConfig({
server: {
port: 4200,
host: 'localhost',
},
plugins: [
react(),
nxViteTsPaths()
],
test: {
globals: true,
cache: {
dir: './node_modules/.vitest',
},
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
reporters: ['junit'],
outputFile: 'junit.xml',
coverage: {
enabled: true,
reportsDirectory: 'coverage',
}
},
});
`;
});
updateJson(join('libs', lib, 'project.json'), (config) => {
delete config.targets.test.options.reportsDirectory;
return config;
});
const projectRoot = `${tmpProjPath()}/libs/${lib}`;
const results = runCLI(`test ${lib}`);
expect(directoryExists(projectRoot)).toBeTruthy();
expect(results).toContain(
`Successfully ran target test for project ${lib}`
);
expect(results).toContain(`JUNIT report written`);
}, 100_000);
it('should be able to run tests with inSourceTests set to true', async () => {
runCLI(
`generate @nx/react:lib ${lib} --unitTestRunner=vitest --inSourceTests`
);
expect(
exists(tmpProjPath(`libs/${lib}/src/lib/${lib}.spec.tsx`))
).toBeFalsy();
updateFile(`libs/${lib}/src/lib/${lib}.tsx`, (content) => {
content += `
if (import.meta.vitest) {
const { expect, it } = import.meta.vitest;
it('should be successful', () => {
expect(1 + 1).toBe(2);
});
}
`;
return content;
});
const result = await runCLIAsync(`test ${lib}`);
expect(result.combinedOutput).toContain(`1 passed`);
}, 100_000);
});
describe('ESM-only apps', () => {
beforeAll(() => {
newProject({ unsetProjectNameAndRootFormat: false });
});
it('should support ESM-only plugins in vite.config.ts for root apps (#NXP-168)', () => {
// ESM-only plugin to test with
updateFile(
'foo/package.json',
JSON.stringify({
name: '@acme/foo',
type: 'module',
version: '1.0.0',
main: 'index.js',
})
);
updateFile(
'foo/index.js',
`
export default function fooPlugin() {
return {
name: 'foo-plugin',
configResolved() {
console.log('Foo plugin');
}
}
}`
);
updateJson('package.json', (json) => {
json.devDependencies['@acme/foo'] = 'file:./foo';
return json;
});
runCommand(getPackageManagerCommand().install);
const rootApp = uniq('root');
runCLI(
`generate @nx/react:app ${rootApp} --rootProject --bundler=vite --unitTestRunner=none --e2eTestRunner=none --style=css --no-interactive`
);
updateJson(`package.json`, (json) => {
// This allows us to use ESM-only packages in vite.config.ts.
json.type = 'module';
return json;
});
updateFile(
`vite.config.ts`,
`
import fooPlugin from '@acme/foo';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
export default defineConfig({
cacheDir: './node_modules/.vite/root-app',
server: {
port: 4200,
host: 'localhost',
},
plugins: [react(), nxViteTsPaths(), fooPlugin()],
});`
);
runCLI(`build ${rootApp}`);
checkFilesExist(`dist/${rootApp}/index.html`);
});
});
});
|
2,078 | 0 | petrpan-code/nrwl/nx/e2e/vue | petrpan-code/nrwl/nx/e2e/vue/src/vue-storybook.test.ts | import {
checkFilesExist,
cleanupProject,
newProject,
runCLI,
setMaxWorkers,
uniq,
} from '@nx/e2e/utils';
import { join } from 'path';
describe('Storybook generators and executors for Vue projects', () => {
const vueStorybookApp = uniq('vue-app');
let proj;
beforeAll(async () => {
proj = newProject();
runCLI(
`generate @nx/vue:app ${vueStorybookApp} --project-name-and-root-format=as-provided --no-interactive`
);
setMaxWorkers(join(vueStorybookApp, 'project.json'));
runCLI(
`generate @nx/vue:storybook-configuration ${vueStorybookApp} --generateStories --no-interactive`
);
});
afterAll(() => {
cleanupProject();
});
describe('build storybook', () => {
it('should build a vue based storybook setup', () => {
// build
runCLI(`run ${vueStorybookApp}:build-storybook --verbose`);
checkFilesExist(`dist/storybook/${vueStorybookApp}/index.html`);
}, 300_000);
});
});
|
Subsets and Splits