Skip to content

Commit

Permalink
chore: migrate to vitest (#181)
Browse files Browse the repository at this point in the history
* started test driving data collector util

* add tests and todos, break fns down a bit

* add fraudnet util

* update correct fn url

* cleanup

* outline of fraudnet work

* ohhhh boy, its messy vitest/flow stuff

* more test crazyiness

* moving server tests and client api to vitest WIP

* lots of tests, lots of inprogress

* graphql tests updated

* lots more tests and such, evaluating the meta things cause ugh

* in prgoress but coming along a ton...merge script and scriptutils tests

* so close. a couple challenges but otherwise so much progress converting to vitest

* so many files done now to fix up some lingering problem tests

* all skipped tests addressed other than logger

* remove client test index and remove msw usage for mocking request

* remove console logs

* remove unused modules and comment out logger test for now

* remove some deps

* remove local env pathin domain

* remove logger from vitest run while evaluate deletion

* remove logger from vitest run while evaluate deletion

* got coverage going for vitest on src files

* use single coverageupload in main flow

* remove mocha

* broken for now thats ok

* start testing fraudnet

* add tests for fraudnet

* spy on logger, handle test for suppressing of all errors

* clear all gql mocks

* removed unneeded files, scriptUtils now all in script.test.js

* Update src/fraudnet.js

* remove unused vars/imports

* remove iteration from single case test

* remove test index, iterate over globals for vitest setup

* make envs a fn for clarity

* clean up vite config file

* so much flow ignore bruh

* nock out some of the lint issues, but not all

* resotre logger domain local block

* fix api test

* forgot to import host and protocol fns

* colocate test files and impl, remove test globals file as not needed

* put test file back since it's used in other repos

* fix globals ref in webpack config

* remove sticky session id use because flow

* remove test ref from lint step

* fix lint errors

* fix flow again

* put make mock element function in helper and adjust to always pass mock url

* fix test lint imports

* add input type for makemockscript

* add test back as an export

* update old coverage ignore lines to work with vitest v8

* move globals vars to own file for webpack and vitest usage

* fix webpack build and ignore hermes flow types

* add back in stickysession once belter updated

* test stickysessionid fix

* remove old codeblock comment

* sort input

---------

Co-authored-by: Shraddha Shah <[email protected]>
  • Loading branch information
cgdibble and siddy2181 authored Jan 23, 2024
1 parent 4018152 commit 3797fde
Show file tree
Hide file tree
Showing 43 changed files with 1,628 additions and 2,243 deletions.
1 change: 1 addition & 0 deletions .flowconfig
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
[ignore]
.*/node_modules/hermes-estree
.*/node_modules/babel-plugin-flow-runtime
.*/node_modules/flow-runtime
.*/node_modules/cross-domain-safe-weakmap/dist
Expand Down
11 changes: 2 additions & 9 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,7 @@ jobs:
- name: ▶️ Run build script
run: npm run build

- name: ⬆️ Upload client coverage report
- name: ⬆️ Upload coverage report
uses: codecov/codecov-action@v3
with:
directory: ./coverage/karma
flags: client

- name: ⬆️ Upload server coverage report
uses: codecov/codecov-action@v3
with:
directory: ./coverage/jest
flags: server
directory: ./coverage
3 changes: 2 additions & 1 deletion babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
/* eslint import/no-commonjs: off */

module.exports = {
extends: "@krakenjs/babel-config-grumbler/babelrc-node",
extends: "@krakenjs/grumbler-scripts/config/.babelrc-node",
presets: ["@krakenjs/babel-config-grumbler/flow-ts-babel-preset"],
};
25 changes: 0 additions & 25 deletions karma.conf.js

This file was deleted.

21 changes: 13 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
"doc": "esdoc",
"flow": "flow",
"flow-typed": "rm -rf ./flow-typed && flow-typed install",
"karma": "cross-env NODE_ENV=test babel-node --plugins=transform-es2015-modules-commonjs ./node_modules/.bin/karma start",
"lint": "eslint src/ server/ test/ *.js",
"lint": "eslint src/ server/ *.js",
"reinstall": "rimraf flow-typed && rimraf node_modules && npm install && flow-typed install",
"release": "./publish.sh",
"release:major": "./publish.sh major",
Expand All @@ -21,9 +20,10 @@
"setup": "npm install && npm run flow-typed",
"format": "prettier --write --ignore-unknown .",
"format:check": "prettier --check .",
"test": "npm run format:check && npm run lint && npm run flow-typed && npm run flow && npm run jest && npm run karma",
"test": "npm run format:check && npm run lint && npm run flow-typed && npm run flow && npm run test:unit",
"webpack": "babel-node --plugins=transform-es2015-modules-commonjs ./node_modules/.bin/webpack --progress",
"jest": "jest test/server --env=node --no-cache --collectCoverageFrom='server/' --coverageDirectory='coverage/jest' --coverage --verbose --runInBand --silent=false",
"test:unit:watch": "vitest --coverage",
"test:unit": "vitest run --coverage",
"prepublishOnly": "npm run babel",
"postpublish": "rm -rf ./server && git checkout ./server",
"validate-codecov": "curl --data-binary @.github/codecov.yml https://codecov.io/validate",
Expand Down Expand Up @@ -62,8 +62,10 @@
"bowser": "^2.0.0"
},
"devDependencies": {
"@bunchtogether/vite-plugin-flow": "^1.0.2",
"@krakenjs/babel-config-grumbler": "^8.1.1",
"@krakenjs/eslint-config-grumbler": "^8.1.1",
"@krakenjs/grumbler-scripts": "^8.0.4",
"@krakenjs/sync-browser-mocks": "^3.0.0",
"babel-core": "7.0.0-bridge.0",
"cheerio": "1.0.0-rc.9",
"cross-env": "^7.0.3",
Expand All @@ -73,10 +75,13 @@
"flow-bin": "0.155.0",
"flow-typed": "^3.8.0",
"husky": "^8.0.1",
"jest": "^29.3.1",
"jsdom": "^20.0.3",
"lint-staged": "^13.0.3",
"mocha": "^10.0.0",
"prettier": "2.8.8"
"prettier": "2.8.8",
"@vitest/coverage-v8": "^1.0.0",
"@vitest/ui": "^1.0.0",
"vite": "^4.0.1",
"vitest": "^1.0.0"
},
"lint-staged": {
"**/*": "prettier --write --ignore-unknown"
Expand Down
3 changes: 2 additions & 1 deletion server/babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
/* eslint import/no-commonjs: off */

module.exports = {
extends: "@krakenjs/babel-config-grumbler/babelrc-node",
extends: "@krakenjs/grumbler-scripts/config/.babelrc-node",
presets: ["@krakenjs/babel-config-grumbler/flow-ts-babel-preset"],
};
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
/* @flow */

import cheerio from "cheerio";
import { test } from "vitest";

import { unpackSDKMeta } from "../../server";
import { unpackSDKMeta } from ".";

/**
* List with real URL query parameters.
Expand Down
3 changes: 2 additions & 1 deletion test/server/meta.test.js → server/meta.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
/* eslint max-lines: off */

import cheerio from "cheerio";
import { test, afterEach } from "vitest";

import { unpackSDKMeta } from "../../server";
import { unpackSDKMeta } from ".";

afterEach(() => {
// eslint-disable-next-line no-process-env
Expand Down
150 changes: 150 additions & 0 deletions src/api.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/* @flow */
import { describe, beforeEach, it, expect, vi } from "vitest";
import { getCurrentScript, request, memoize } from "@krakenjs/belter/src";

import { createAccessToken, createOrder } from "./api";

vi.mock("@krakenjs/belter/src", async () => {
const actual = await vi.importActual("@krakenjs/belter/src");
return {
...actual,
getCurrentScript: vi.fn(),
request: vi.fn().mockResolvedValue(),
};
});

describe("api cases", () => {
let order;
const invalidClientId = "invalid-client-id";
const emptyResponseClientId = "empty-response-client-id";
const createOrderValidId = "create-order-valid-order-id";
const expectedToken =
"A21AAKNZBaqilFBC4dVVz-tr-ySIT78NREeBidy3lkGdr-EA8wbhGrByPayhgnJRPE5xg4QW46moDbCFjZ13i1GH-Ax4SjtjA";
const defaultAuthResponse = {
scope: "https://uri.paypal.com/services/invoicing",
access_token: expectedToken,
token_type: "Bearer",
app_id: "APP-80W284485P519543T",
expires_in: 31838,
nonce: "2022-03-07T22:41:38ZqHkiC0_odfzFwo27_X0wVuF67STYq39KRplBeeyY2bk",
error: null,
};

beforeEach(() => {
memoize.clear();
window.__PAYPAL_DOMAIN__ = "testurl";
// $FlowIgnore
getCurrentScript.mockReturnValue({
src: `https://sdkplz.com/sdk/js?intent=capture`,
attributes: [],
});
vi.clearAllMocks();

order = {
intent: "CAPTURE",
purchase_units: [
{
amount: {
value: "10.00",
currency_code: "USD",
},
},
],
};
});

describe("createAccessToken()", () => {
it("createAccessToken should return a valid token", async () => {
// $FlowIgnore
request.mockResolvedValueOnce({ body: defaultAuthResponse });

const result = await createAccessToken("testClient");

expect(result).toEqual(expectedToken);
});

it("createAccessToken should throw invalid client argument error", async () => {
// $FlowIgnore
request.mockResolvedValueOnce({ body: { error: "invalid_client" } });

await expect(() =>
createAccessToken(invalidClientId)
).rejects.toThrowError(/Auth Api invalid client id:/);
});

it("createAccessToken should return an error message when response is an empty object", async () => {
// $FlowIgnore
request.mockResolvedValueOnce({ body: {} });

await expect(() =>
createAccessToken(emptyResponseClientId)
).rejects.toThrow(/Auth Api response error:/);
});
});

describe("createOrder()", () => {
it("createOrder should throw an error when clientId is null", () => {
// $FlowIgnore
expect(() => createOrder(null)).toThrowError(/Client ID not passed/);
});

it("createOrder should throw an error when order is null", () => {
// $FlowIgnore
expect(() => createOrder("testClient", null)).toThrow(
/Expected order details to be passed/
);
});

it("createOrder should throw an error when order intent does not match with query parameters intent", () => {
const expectedErrorMessage =
"Unexpected intent: AUTHORIZE passed to order.create. Please ensure you are passing /sdk/js?intent=authorize in the paypal script tag.";

order.intent = "AUTHORIZE";

expect(() => createOrder("testClient", order)).toThrowError(
expectedErrorMessage
);
});

it("createOrder should throw an error when order currency does not match with query parameters currency", () => {
const expectedErrorMessage =
"Unexpected currency: AUD passed to order.create. Please ensure you are passing /sdk/js?currency=AUD in the paypal script tag.";
order.purchase_units[0].amount.currency_code = "AUD";

expect(() => createOrder("testClient", order)).toThrow(
expectedErrorMessage
);
});

it("createOrder should throw an error when order identifier is not in the server response", async () => {
const expectedErrorMessage = "Order Api response error:";
const failuredPayload = {};

request
// $FlowIgnore
.mockResolvedValueOnce({ body: defaultAuthResponse })
.mockResolvedValueOnce({ body: failuredPayload });

await expect(() => createOrder("testClient", order)).rejects.toThrow(
expectedErrorMessage
);
});

it("createOrder should return a valid orderId", async () => {
const expectedOrderId = "9BL31648CM342010L";
const mockOrderResponse = {
id: expectedOrderId,
status: "CREATED",
links: [],
};

request
// $FlowIgnore
.mockResolvedValueOnce({ body: defaultAuthResponse })
.mockResolvedValueOnce({ body: mockOrderResponse });

const result = await createOrder(createOrderValidId, order);
expect(result).toEqual(expectedOrderId);
});
});
});
39 changes: 39 additions & 0 deletions src/config.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/* @flow */
import { describe, it, expect } from "vitest";

import {
getPayPalLoggerDomain,
buildPayPalUrl,
buildPayPalAPIUrl,
getPayPalLoggerUrl,
} from "./domains";

describe(`config cases`, () => {
it("should successfully get the global paypal logger domain", () => {
const expectedDomain = "mock://www.paypal.com";
window.__PAYPAL_DOMAIN__ = expectedDomain;
const domain = getPayPalLoggerDomain();
expect(domain).toEqual(expectedDomain);
});

it("should successfully build a paypal url", () => {
const expectedPayPalUrl = `${window.location.protocol}//${window.location.host}/foo/bar`;
const result = buildPayPalUrl("/foo/bar");

expect(result).toEqual(expectedPayPalUrl);
});

it("should successfully build a paypal api url", () => {
const expectedPayPalUrl = `${window.location.protocol}//${window.location.host}/bar/baz`;
const result = buildPayPalAPIUrl("/bar/baz");

expect(result).toEqual(expectedPayPalUrl);
});

it("should successfully build a paypal logger url", () => {
const expectedPayPalUrl = `${window.location.protocol}//${window.location.host}/xoplatform/logger/api/logger`;
const result = getPayPalLoggerUrl();

expect(result).toEqual(expectedPayPalUrl);
});
});
4 changes: 2 additions & 2 deletions src/domains.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import {
} from "@krakenjs/cross-domain-utils/src";

import {
getPayPalAPIDomain,
getPayPalDomain,
getProtocol,
getStageHost,
getPayPalDomain,
getPayPalAPIDomain,
} from "./global";
import { URI } from "./config";

Expand Down
Loading

0 comments on commit 3797fde

Please sign in to comment.