Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: add initial integration test suite #371

Merged
merged 17 commits into from
Jul 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@
*.swp
*.swo
coverage
__tests__/__temp/
__temp
6 changes: 3 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ Use the [standard GitHub process](https://docs.github.com/en/pull-requests/colla
1. `npm run test:watch` to run tests in watch mode while developing
1. `npm run test:coverage` to run tests and output a test coverage report

While this repo now has an assortment of unit tests, it still badly needs integration tests with various scenarios and expected outcomes.
Test coverage improvements for existing files and untested is needed as well.
While this repo now has an assortment of unit tests and integration tests, it still needs more integration tests with various scenarios and expected outcomes.
Test coverage improvements for existing files and untested files is needed as well.

### Building and Self-Build

Expand Down Expand Up @@ -72,7 +72,7 @@ A useful resource as you dive deeper are the [unit tests](__tests__/). They're g
- [Using the Language Service API](https://github.com/microsoft/TypeScript/wiki/Using-the-Language-Service-API)
- _NOTE_: These are fairly short and unfortunately leave a lot to be desired... especially when you consider that this plugin is actually one of the simpler integrations out there.
1. At this point, you may be ready to read the more complicated bits of [`index`](src/index.ts) in detail and see how it interacts with the other modules.
- The integration tests [TBD] could be useful to review at this point as well.
- The [integration tests](__tests__/integration/) could be useful to review at this point as well.
1. Once you're pretty familiar with `index`, you can dive into some of the cache code in [`tscache`](src/tscache.ts) and [`rollingcache`](src/rollingcache.ts).
1. And finally, you can see some of the Rollup logging nuances in [`context`](src/context.ts) and [`rollupcontext`](src/rollupcontext.ts), and then the TS logging nuances in [`print-diagnostics`](src/print-diagnostics.ts), and [`diagnostics-format-host`](src/diagnostics-format-host.ts)
- While these are necessary to the implementation, they are fairly ancillary to understanding and working with the codebase.
66 changes: 66 additions & 0 deletions __tests__/integration/errors.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { jest, afterAll, test, expect } from "@jest/globals";
import * as path from "path";
import { normalizePath as normalize } from "@rollup/pluginutils";
import * as fs from "fs-extra";
import { red } from "colors/safe";

import { RPT2Options } from "../../src/index";
import * as helpers from "./helpers";

// increase timeout to 15s for whole file since CI occassionally timed out -- these are integration and cache tests, so longer timeout is warranted
jest.setTimeout(15000);

const local = (x: string) => path.resolve(__dirname, x);
const cacheRoot = local("__temp/errors/rpt2-cache"); // don't use the one in node_modules
const onwarn = jest.fn();

afterAll(async () => {
// workaround: there seems to be some race condition causing fs.remove to fail, so give it a sec first (c.f. https://github.com/jprichardson/node-fs-extra/issues/532)
await new Promise(resolve => setTimeout(resolve, 1000));
await fs.remove(cacheRoot);
});

async function genBundle(relInput: string, extraOpts?: RPT2Options) {
const input = normalize(local(`fixtures/errors/${relInput}`));
return helpers.genBundle({
input,
tsconfig: local("fixtures/errors/tsconfig.json"),
cacheRoot,
extraOpts: { include: [input], ...extraOpts }, // only include the input itself, not other error files (to only generate types and type-check the one file)
onwarn,
});
}

test("integration - tsconfig errors", async () => {
// TODO: move to parse-tsconfig unit tests?
expect(genBundle("semantic.ts", {
tsconfig: "non-existent-tsconfig",
})).rejects.toThrow("rpt2: failed to open 'undefined'"); // FIXME: bug: this should be "non-existent-tsconfig", not "undefined"
});

test("integration - semantic error", async () => {
expect(genBundle("semantic.ts")).rejects.toThrow(`semantic error TS2322: ${red("Type 'string' is not assignable to type 'number'.")}`);
});

test("integration - semantic error - abortOnError: false / check: false", async () => {
// either warning or not type-checking should result in the same bundle
const { output } = await genBundle("semantic.ts", { abortOnError: false });
const { output: output2 } = await genBundle("semantic.ts", { check: false });
expect(output).toEqual(output2);

expect(output[0].fileName).toEqual("index.js");
expect(output[1].fileName).toEqual("semantic.d.ts");
expect(output[2].fileName).toEqual("semantic.d.ts.map");
expect(output.length).toEqual(3); // no other files
expect(onwarn).toBeCalledTimes(1);
});

test("integration - syntax error", () => {
expect(genBundle("syntax.ts")).rejects.toThrow(`syntax error TS1005: ${red("';' expected.")}`);
});

test("integration - syntax error - abortOnError: false / check: false", () => {
const err = "Unexpected token (Note that you need plugins to import files that are not JavaScript)";
expect(genBundle("syntax.ts", { abortOnError: false })).rejects.toThrow(err);
expect(genBundle("syntax.ts", { check: false })).rejects.toThrow(err);
});
3 changes: 3 additions & 0 deletions __tests__/integration/fixtures/errors/semantic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const sum = (a: number, b: number): number => {
return "a + b";
}
3 changes: 3 additions & 0 deletions __tests__/integration/fixtures/errors/syntax.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const incorrectSyntax => {
return "a + b";
}
3 changes: 3 additions & 0 deletions __tests__/integration/fixtures/errors/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "../tsconfig.json",
}
8 changes: 8 additions & 0 deletions __tests__/integration/fixtures/no-errors/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export function sum(a: number, b: number) {
return a + b;
}

export { difference } from "./some-import"
export type { num } from "./type-only-import"

export { identity } from "./some-js-import"
3 changes: 3 additions & 0 deletions __tests__/integration/fixtures/no-errors/some-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function difference(a: number, b: number) {
return a - b;
}
4 changes: 4 additions & 0 deletions __tests__/integration/fixtures/no-errors/some-js-import.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// TS needs a declaration in order to understand the import
// but this is ambient, and so should not be directly imported into rpt2, just found by TS

export function identity(a: any): any;
5 changes: 5 additions & 0 deletions __tests__/integration/fixtures/no-errors/some-js-import.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// should be filtered out by rpt2, but still bundled by Rollup itself (as this is ESM, no need for a plugin)

export function identity(a) {
return a;
}
3 changes: 3 additions & 0 deletions __tests__/integration/fixtures/no-errors/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "../tsconfig.json",
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type num = number;
11 changes: 11 additions & 0 deletions __tests__/integration/fixtures/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"sourceMap": true,
"declaration": true,
"declarationMap": true,
"target": "ES6",
"strict": true,
},
}
41 changes: 41 additions & 0 deletions __tests__/integration/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { rollup, RollupOptions, OutputAsset } from "rollup";

import rpt2, { RPT2Options } from "../../src/index";

type Params = {
input: string,
tsconfig: string,
cacheRoot: string,
extraOpts?: RPT2Options,
onwarn?: RollupOptions['onwarn'],
};

export async function genBundle ({ input, tsconfig, cacheRoot, extraOpts, onwarn }: Params) {
const bundle = await rollup({
input,
plugins: [rpt2({
tsconfig,
cacheRoot,
...extraOpts,
})],
onwarn,
});

const esm = await bundle.generate({
file: "./dist/index.js",
format: "esm",
exports: "named",
});

// Rollup has some deprecated properties like `get isAsset`, so enumerating them with, e.g. `.toEqual`, causes a bunch of warnings to be output
// delete the `isAsset` property for (much) cleaner logs
const { output: files } = esm;
for (const file of files) {
if ("isAsset" in file) {
const optIsAsset = file as Partial<Pick<OutputAsset, "isAsset">> & Omit<OutputAsset, "isAsset">;
delete optIsAsset["isAsset"];
}
}

return esm;
}
91 changes: 91 additions & 0 deletions __tests__/integration/no-errors.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { jest, afterAll, test, expect } from "@jest/globals";
import * as path from "path";
import * as fs from "fs-extra";

import { RPT2Options } from "../../src/index";
import * as helpers from "./helpers";

// increase timeout to 15s for whole file since CI occassionally timed out -- these are integration and cache tests, so longer timeout is warranted
jest.setTimeout(15000);

const local = (x: string) => path.resolve(__dirname, x);
const cacheRoot = local("__temp/no-errors/rpt2-cache"); // don't use the one in node_modules

afterAll(() => fs.remove(cacheRoot));

async function genBundle(relInput: string, extraOpts?: RPT2Options) {
return helpers.genBundle({
input: local(`fixtures/no-errors/${relInput}`),
tsconfig: local("fixtures/no-errors/tsconfig.json"),
cacheRoot,
extraOpts,
});
}

test("integration - no errors", async () => {
const { output } = await genBundle("index.ts", { clean: true });

// populate the cache
await genBundle("index.ts");
const { output: outputWithCache } = await genBundle("index.ts");
expect(output).toEqual(outputWithCache);

expect(output[0].fileName).toEqual("index.js");
expect(output[1].fileName).toEqual("index.d.ts");
expect(output[2].fileName).toEqual("index.d.ts.map");
expect(output[3].fileName).toEqual("some-import.d.ts");
expect(output[4].fileName).toEqual("some-import.d.ts.map");
expect(output[5].fileName).toEqual("type-only-import.d.ts");
expect(output[6].fileName).toEqual("type-only-import.d.ts.map");
expect(output.length).toEqual(7); // no other files

// JS file should be bundled by Rollup, even though rpt2 does not resolve it (as Rollup natively understands ESM)
expect(output[0].code).toEqual(expect.stringContaining("identity"));
});

test("integration - no errors - no declaration maps", async () => {
const noDeclarationMaps = { compilerOptions: { declarationMap: false } };
const { output } = await genBundle("index.ts", {
tsconfigOverride: noDeclarationMaps,
clean: true,
});

expect(output[0].fileName).toEqual("index.js");
expect(output[1].fileName).toEqual("index.d.ts");
expect(output[2].fileName).toEqual("some-import.d.ts");
expect(output[3].fileName).toEqual("type-only-import.d.ts");
expect(output.length).toEqual(4); // no other files
});


test("integration - no errors - no declarations", async () => {
const noDeclarations = { compilerOptions: { declaration: false, declarationMap: false } };
const { output } = await genBundle("index.ts", {
tsconfigOverride: noDeclarations,
clean: true,
});

expect(output[0].fileName).toEqual("index.js");
expect(output.length).toEqual(1); // no other files
});

test("integration - no errors - allowJs + emitDeclarationOnly", async () => {
const { output } = await genBundle("some-js-import.js", {
include: ["**/*.js"],
tsconfigOverride: {
compilerOptions: {
allowJs: true,
emitDeclarationOnly: true,
},
},
});

expect(output[0].fileName).toEqual("index.js");
expect(output[1].fileName).toEqual("some-js-import.d.ts");
expect(output[2].fileName).toEqual("some-js-import.d.ts.map");
expect(output.length).toEqual(3); // no other files

expect(output[0].code).toEqual(expect.stringContaining("identity"));
expect(output[0].code).not.toEqual(expect.stringContaining("sum")); // no TS files included
expect("source" in output[1] && output[1].source).toEqual(expect.stringContaining("identity"));
});
10 changes: 9 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
/** @type {import("@jest/types").Config.InitialOptions} */
/** @type {import("ts-jest").InitialOptionsTsJest} */
const config = {
// ts-jest settings
preset: "ts-jest",
globals: {
"ts-jest": {
tsconfig: "./tsconfig.test.json",
}
},

// jest settings
injectGlobals: false, // use @jest/globals instead
restoreMocks: true,
// only use *.spec.ts files in __tests__, no auto-generated files
Expand Down
6 changes: 6 additions & 0 deletions tsconfig.test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"extends": "./tsconfig",
"compilerOptions": {
"esModuleInterop": true, // needed to parse some imports with ts-jest (since Rollup isn't used when importing during testing)
},
}