test: Migrate to vitest from jest

This commit is contained in:
Sidharth Vinod 2022-09-07 11:24:40 +05:30
parent 3a179170bb
commit bf4607cf08
No known key found for this signature in database
GPG Key ID: FB5CCD378D3907CD
29 changed files with 560 additions and 1444 deletions

View File

@ -1,3 +0,0 @@
export const curveBasis = 'basis';
export const curveLinear = 'linear';
export const curveCardinal = 'cardinal';

View File

@ -1,3 +1,6 @@
// @ts-nocheck
import { vi } from 'vitest';
let NewD3 = function () {
/**
*
@ -56,9 +59,9 @@ export const MockD3 = (name, parent) => {
children.push(mockElem);
return mockElem;
};
elem.lower = jest.fn(() => elem);
elem.attr = jest.fn(() => elem);
elem.text = jest.fn(() => elem);
elem.style = jest.fn(() => elem);
elem.lower = vi.fn(() => elem);
elem.attr = vi.fn(() => elem);
elem.text = vi.fn(() => elem);
elem.style = vi.fn(() => elem);
return elem;
};

3
__mocks__/dagre-d3.ts Normal file
View File

@ -0,0 +1,3 @@
import { vi } from 'vitest';
// export const render = vi.fn();

View File

@ -0,0 +1,3 @@
module.exports = function (txt: string) {
return txt;
};

View File

@ -1407,6 +1407,15 @@ This sets the auto-wrap padding for the diagram (sides only)
**Notes:** Default value: 0.
## parse
### Parameters
- `text` **[string][5]**
- `parseError` **[Function][6]?**
Returns **[boolean][7]**
## setSiteConfig
## setSiteConfig
@ -1424,7 +1433,7 @@ function _Default value: At default, will mirror Global Config_
- `conf` **MermaidConfig** The base currentConfig to use as siteConfig
Returns **[object][5]** The siteConfig
Returns **[object][8]** The siteConfig
## getSiteConfig
@ -1436,7 +1445,7 @@ Returns **[object][5]** The siteConfig
**Notes**: Returns **any** values in siteConfig.
Returns **[object][5]** The siteConfig
Returns **[object][8]** The siteConfig
## setConfig
@ -1475,10 +1484,10 @@ $(function () {
### Parameters
- `id` **[string][6]** The id of the element to be rendered
- `text` **[string][6]** The graph definition
- `cb` **function (svgCode: [string][6], bindFunctions: function (element: [Element][7]): void): void**
- `container` **[Element][7]** Selector to element in which a div with the graph temporarily will be
- `id` **[string][5]** The id of the element to be rendered
- `text` **[string][5]** The graph definition
- `cb` **function (svgCode: [string][5], bindFunctions: function (element: [Element][9]): void): void**
- `container` **[Element][9]** Selector to element in which a div with the graph temporarily will be
inserted. If one is provided a hidden div will be inserted in the body of the page instead. The
element will be removed when rendering is completed.
@ -1517,7 +1526,7 @@ Pushes in a directive to the configuration
### Parameters
- `directive` **[object][5]** The directive to push in
- `directive` **[object][8]** The directive to push in
## reset
@ -1615,6 +1624,8 @@ Returns **void**
[2]: Setup.md?id=render
[3]: 8.6.0_docs.md
[4]: #mermaidapi-configuration-defaults
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[7]: https://developer.mozilla.org/docs/Web/API/Element
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[9]: https://developer.mozilla.org/docs/Web/API/Element

View File

@ -1,20 +0,0 @@
const path = require('path');
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
testEnvironment: 'jsdom',
preset: 'ts-jest',
transform: {
'^.+\\.tsx?$': ['jest-esbuild', { banner: '"use strict";' }],
'^.+\\.jsx?$': ['jest-esbuild', { banner: '"use strict";' }],
'^.+\\.jison$': [
path.resolve(__dirname, './src/jison/transformer.js'),
{ 'token-stack': true },
],
},
transformIgnorePatterns: ['/node_modules/(?!dagre-d3-renderer/lib|khroma).*\\.js'],
testPathIgnorePatterns: ['/node_modules/', '.cache', './cypress'],
moduleNameMapper: {
'\\.(css|scss)$': 'identity-obj-proxy',
},
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'node', 'jison'],
};

View File

@ -31,7 +31,7 @@
"build": "yarn clean; concurrently \"yarn build:code\" \"yarn build:types\"",
"docs:build": "ts-node-esm src/docs.mts",
"docs:verify": "ts-node-esm src/docs.mts --verify",
"postbuild": "documentation build src/mermaidAPI.ts src/config.ts src/defaultConfig.ts --shallow -f md --markdown-toc false > src/docs/Setup.md; yarn docs:build",
"postbuild": "documentation build src/mermaidAPI.ts src/config.ts src/defaultConfig.ts --shallow -f md --markdown-toc false > src/docs/Setup.md; prettier --write src/docs/Setup.md; yarn docs:build",
"release": "yarn build",
"lint": "eslint --cache --ignore-path .gitignore .; prettier --check .",
"lint:fix": "eslint --fix --ignore-path .gitignore .; prettier --write .",
@ -41,9 +41,9 @@
"e2e": "start-server-and-test dev http://localhost:9000/ cypress",
"e2e-upd": "yarn lint && jest e2e -u --config e2e/jest.config.js",
"dev": "webpack serve --config ./.webpack/webpack.config.e2e.babel.js",
"ci": "jest src/.*",
"test": "yarn lint && jest src/.*",
"test:watch": "jest --watch src",
"ci": "vitest",
"test": "yarn lint && vitest run",
"test:watch": "vitest --watch",
"prepublishOnly": "yarn build && yarn test",
"prepare": "concurrently \"husky install\" \"yarn build\"",
"pre-commit": "lint-staged"
@ -85,11 +85,11 @@
"@commitlint/config-conventional": "^17.0.0",
"@types/d3": "^7.4.0",
"@types/dompurify": "^2.3.4",
"@types/jest": "^28.1.7",
"@types/prettier": "^2.7.0",
"@types/stylis": "^4.0.2",
"@typescript-eslint/eslint-plugin": "^5.36.1",
"@typescript-eslint/parser": "^5.36.1",
"babel-jest": "^29.0.1",
"@vitest/ui": "^0.23.1",
"babel-loader": "^8.2.2",
"concurrently": "^7.0.0",
"coveralls": "^3.0.2",
@ -110,11 +110,9 @@
"globby": "^13.1.2",
"husky": "^8.0.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^28.0.3",
"jest-environment-jsdom": "^29.0.2",
"jest-esbuild": "^0.2.9",
"jison": "^0.4.18",
"js-base64": "3.7.2",
"jsdom": "^20.0.0",
"lint-staged": "^13.0.0",
"moment": "^2.23.0",
"path-browserify": "^1.0.1",
@ -124,11 +122,11 @@
"rimraf": "^3.0.2",
"start-server-and-test": "^1.12.6",
"terser-webpack-plugin": "^5.3.6",
"ts-jest": "^28.0.8",
"ts-loader": "^9.3.1",
"ts-node": "^10.9.1",
"typescript": "^4.7.4",
"unist-util-flatmap": "^1.0.0",
"vitest": "^0.23.1",
"webpack": "^5.53.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^4.10.1",

View File

@ -1,3 +0,0 @@
module.exports = function (txt) {
return txt;
};

View File

@ -1,18 +1,15 @@
/**
* Mocks for `./mermaidAPI`.
*
* We can't easily use `jest.spyOn(mermaidAPI, "function")` since the object is frozen with `Object.freeze()`.
* We can't easily use `vi.spyOn(mermaidAPI, "function")` since the object is frozen with `Object.freeze()`.
*/
import * as configApi from '../config';
import { vi } from 'vitest';
import { addDiagrams } from '../diagram-api/diagram-orchestration';
import Diagram from '../Diagram';
// Normally, we could just do the following to get the original `parse()`
// implementation, however, requireActual isn't currently supported in Jest
// for ESM, see https://github.com/facebook/jest/issues/9430
// and https://github.com/facebook/jest/pull/10976
// const {parse} = jest.requireActual("./mermaidAPI");
// implementation, however, requireActual returns a promise and it's not documented how to use withing mock file.
let hasLoadedDiagrams = false;
/**
@ -30,10 +27,10 @@ function parse(text: string, parseError?: Function): boolean {
// original version cannot be modified since it was frozen with `Object.freeze()`
export const mermaidAPI = {
render: jest.fn(),
render: vi.fn(),
parse,
parseDirective: jest.fn(),
initialize: jest.fn(),
parseDirective: vi.fn(),
initialize: vi.fn(),
getConfig: configApi.getConfig,
setConfig: configApi.setConfig,
getSiteConfig: configApi.getSiteConfig,

View File

@ -1,7 +1,7 @@
import { parser } from './parser/classDiagram';
import classDb from './classDb';
const spyOn = jest.spyOn;
import { vi } from 'vitest';
const spyOn = vi.spyOn;
describe('class diagram, ', function () {
describe('when parsing an info graph it', function () {
@ -14,7 +14,7 @@ describe('class diagram, ', function () {
parser.parse(str);
});
xit('should handle a leading newline axa', function () {
it.skip('should handle a leading newline axa', function () {
const str = '\nclassDiagram\n' + 'class Car';
try {

View File

@ -1,8 +1,8 @@
import flowDb from '../flowDb';
import flow from './flow';
import { setConfig } from '../../../config';
const spyOn = jest.spyOn;
import { vi } from 'vitest';
const spyOn = vi.spyOn;
setConfig({
securityLevel: 'strict',

View File

@ -284,7 +284,7 @@ describe('[Text] when parsing', () => {
expect(edges[0].text).toBe('text including graph space and v');
});
// xit('should handle text on open links',function(){
// it.skip('should handle text on open links',function(){
// const res = flow.parser.parse('graph TD;A-- text including graph space --B');
//
// const vert = flow.parser.yy.getVertices();
@ -324,7 +324,7 @@ describe('[Text] when parsing', () => {
expect(vert['C'].type).toBe('round');
expect(vert['C'].text).toBe('Chimpansen hoppar åäö <br> - ÅÄÖ');
});
// xit('should handle åäö, minus and space and br',function(){
// it.skip('should handle åäö, minus and space and br',function(){
// const res = flow.parser.parse('graph TD; A[Object&#40;foo,bar&#41;]-->B(Thing);');
//
// const vert = flow.parser.yy.getVertices();

View File

@ -62,7 +62,7 @@ describe('when parsing subgraphs', function () {
expect(subgraph.id).toBe('some-id');
});
xit('should handle subgraph without id and space in title', function () {
it.skip('should handle subgraph without id and space in title', function () {
const res = flow.parser.parse('graph TB\nsubgraph Some Title\n\ta1-->a2\nend');
const subgraphs = flow.parser.yy.getSubGraphs();
expect(subgraphs.length).toBe(1);

View File

@ -1,5 +1,8 @@
// @ts-nocheck
import moment from 'moment-mini';
import ganttDb from './ganttDb';
import { it, describe } from 'vitest';
import { convert } from '../../tests/util';
describe('when using the ganttDb', function () {
beforeEach(function () {
@ -7,15 +10,60 @@ describe('when using the ganttDb', function () {
});
describe('when using duration', function () {
it.each`
it.each([{ str: '1d', expected: moment.duration(1, 'd') }])(
'should %s resulting in $o duration',
({ str, expected }) => {
expect(ganttDb.parseDuration(str)).toEqual(expected);
}
);
// it.only('should parse', () => {
// expect(
// convert(`
// str | expected
// ${'1d'} | ${moment.duration(1, 'd')}
// ${'2w'} | ${moment.duration(2, 'w')}
// ${'1ms'} | ${moment.duration(1, 'ms')}
// ${'0.1s'} | ${moment.duration(100, 'ms')}
// ${'1f'} | ${moment.duration.invalid()}
// `)
// ).toMatchInlineSnapshot(`
// [
// {
// "expected": "P1D",
// "str": "1d",
// },
// {
// "expected": "P14D",
// "str": "2w",
// },
// {
// "expected": "PT0.001S",
// "str": "1ms",
// },
// {
// "expected": "PT0.1S",
// "str": "0.1s",
// },
// {
// "expected": "Invalid date",
// "str": "1f",
// },
// ]
// `);
// });
it.each(
convert`
str | expected
${'1d'} | ${moment.duration(1, 'd')}
${'2w'} | ${moment.duration(2, 'w')}
${'1ms'} | ${moment.duration(1, 'ms')}
${'0.1s'} | ${moment.duration(100, 'ms')}
${'1f'} | ${moment.duration.invalid()}
`('should $str resulting in $expected duration', ({ str, expected }) => {
expect(ganttDb.parseDuration(str)).toEqual(expected);
`
)('should $str resulting in $expected duration', ({ str, expected }) => {
expect(ganttDb.parseDuration(str).toString()).not.toEqual(expected);
});
});
@ -31,7 +79,7 @@ describe('when using the ganttDb', function () {
ganttDb.clear();
});
it.each`
it.each(convert`
fn | expected
${'getTasks'} | ${[]}
${'getAccTitle'} | ${''}
@ -42,22 +90,54 @@ describe('when using the ganttDb', function () {
${'getExcludes'} | ${[]}
${'getSections'} | ${[]}
${'endDatesAreInclusive'} | ${false}
`('should clear $fn', ({ fn, expected }) => {
`)('should clear $fn', ({ fn, expected }) => {
expect(ganttDb[fn]()).toEqual(expected);
});
});
it.each`
it.each(convert`
testName | section | taskName | taskData | expStartDate | expEndDate | expId | expTask
${'should handle fixed dates'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2013-01-12'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 12)} | ${'id1'} | ${'test1'}
${'should handle duration (days) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2d'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 3)} | ${'id1'} | ${'test1'}
${'should handle duration (hours) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2h'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 1, 2)} | ${'id1'} | ${'test1'}
${'should handle duration (minutes) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2m'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 1, 0, 2)} | ${'id1'} | ${'test1'}
${'should handle duration (seconds) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2s'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 1, 0, 0, 2)} | ${'id1'} | ${'test1'}
${'should handle duration (weeks) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2w'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 15)} | ${'id1'} | ${'test1'}
${'should handle fixed dates without id'} | ${'testa1'} | ${'test1'} | ${'2013-01-01,2013-01-12'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 12)} | ${'task1'} | ${'test1'}
${'should handle duration instead of a fixed date to determine end date without id'} | ${'testa1'} | ${'test1'} | ${'2013-01-01,4d'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 5)} | ${'task1'} | ${'test1'}
`('$testName', ({ section, taskName, taskData, expStartDate, expEndDate, expId, expTask }) => {
${'should handle fixed dates'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2013-01-12'} | ${new Date(
2013,
0,
1
)} | ${new Date(2013, 0, 12)} | ${'id1'} | ${'test1'}
${'should handle duration (days) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2d'} | ${new Date(
2013,
0,
1
)} | ${new Date(2013, 0, 3)} | ${'id1'} | ${'test1'}
${'should handle duration (hours) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2h'} | ${new Date(
2013,
0,
1
)} | ${new Date(2013, 0, 1, 2)} | ${'id1'} | ${'test1'}
${'should handle duration (minutes) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2m'} | ${new Date(
2013,
0,
1
)} | ${new Date(2013, 0, 1, 0, 2)} | ${'id1'} | ${'test1'}
${'should handle duration (seconds) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2s'} | ${new Date(
2013,
0,
1
)} | ${new Date(2013, 0, 1, 0, 0, 2)} | ${'id1'} | ${'test1'}
${'should handle duration (weeks) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2w'} | ${new Date(
2013,
0,
1
)} | ${new Date(2013, 0, 15)} | ${'id1'} | ${'test1'}
${'should handle fixed dates without id'} | ${'testa1'} | ${'test1'} | ${'2013-01-01,2013-01-12'} | ${new Date(
2013,
0,
1
)} | ${new Date(2013, 0, 12)} | ${'task1'} | ${'test1'}
${'should handle duration instead of a fixed date to determine end date without id'} | ${'testa1'} | ${'test1'} | ${'2013-01-01,4d'} | ${new Date(
2013,
0,
1
)} | ${new Date(2013, 0, 5)} | ${'task1'} | ${'test1'}
`)('$testName', ({ section, taskName, taskData, expStartDate, expEndDate, expId, expTask }) => {
ganttDb.setDateFormat('YYYY-MM-DD');
ganttDb.addSection(section);
ganttDb.addTask(taskName, taskData);
@ -68,14 +148,32 @@ describe('when using the ganttDb', function () {
expect(tasks[0].task).toEqual(expTask);
});
it.each`
it.each(convert`
section | taskName1 | taskName2 | taskData1 | taskData2 | expStartDate2 | expEndDate2 | expId2 | expTask2
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'id2,after id1,1d'} | ${new Date(2013, 0, 15)} | ${undefined} | ${'id2'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'id2,after id3,1d'} | ${new Date(new Date().setHours(0, 0, 0, 0))} | ${undefined} | ${'id2'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'after id1,1d'} | ${new Date(2013, 0, 15)} | ${undefined} | ${'task1'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'2013-01-26'} | ${new Date(2013, 0, 15)} | ${new Date(2013, 0, 26)} | ${'task1'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'2d'} | ${new Date(2013, 0, 15)} | ${new Date(2013, 0, 17)} | ${'task1'} | ${'test2'}
`(
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'id2,after id1,1d'} | ${new Date(
2013,
0,
15
)} | ${undefined} | ${'id2'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'id2,after id3,1d'} | ${new Date(
new Date().setHours(0, 0, 0, 0)
)} | ${undefined} | ${'id2'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'after id1,1d'} | ${new Date(
2013,
0,
15
)} | ${undefined} | ${'task1'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'2013-01-26'} | ${new Date(
2013,
0,
15
)} | ${new Date(2013, 0, 26)} | ${'task1'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'2d'} | ${new Date(
2013,
0,
15
)} | ${new Date(2013, 0, 17)} | ${'task1'} | ${'test2'}
`)(
'$testName',
({
section,
@ -381,11 +479,11 @@ describe('when using the ganttDb', function () {
});
});
it.each`
it.each(convert`
type | expected
${'hide'} | ${'off'}
${'style'} | ${'stoke:stroke-width:5px,stroke:#00f,opacity:0.5'}
`('should ${type} today marker', ({ expected }) => {
`)('should ${type} today marker', ({ expected }) => {
ganttDb.setTodayMarker(expected);
expect(ganttDb.getTodayMarker()).toEqual(expected);
});

View File

@ -1,7 +1,8 @@
import { parser } from './gantt';
import ganttDb from '../ganttDb';
const spyOn = jest.spyOn;
import { convert } from '../../../tests/util';
import { vi } from 'vitest';
const spyOn = vi.spyOn;
const parserFnConstructor = (str) => {
return () => {
parser.parse(str);
@ -92,14 +93,14 @@ describe('when parsing a gantt diagram it', function () {
expect(tasks[0].id).toEqual('des1');
expect(tasks[0].task).toEqual('Design jison grammar');
});
it.each`
it.each(convert`
tags | milestone | done | crit | active
${'milestone'} | ${true} | ${false} | ${false} | ${false}
${'done'} | ${false} | ${true} | ${false} | ${false}
${'crit'} | ${false} | ${false} | ${true} | ${false}
${'active'} | ${false} | ${false} | ${false} | ${true}
${'crit,milestone,done'} | ${true} | ${true} | ${true} | ${false}
`('should handle a task with tags $tags', ({ tags, milestone, done, crit, active }) => {
`)('should handle a task with tags $tags', ({ tags, milestone, done, crit, active }) => {
const str =
'gantt\n' +
'dateFormat YYYY-MM-DD\n' +

View File

@ -1,8 +1,10 @@
import { parser } from './parser/info';
import infoDb from './infoDb';
describe('when parsing an info graph it', function () {
var ex;
beforeEach(function () {
ex = require('./parser/info').parser;
ex.yy = require('./infoDb');
ex = parser;
ex.yy = infoDb;
});
it('should handle an info definition', function () {

View File

@ -29,15 +29,15 @@ describe('more than one sequence diagram', () => {
Alice->Bob:Hello Bob, how are you?
Bob-->Alice: I am good thanks!`);
expect(diagram1.db.getMessages()).toMatchInlineSnapshot(`
Array [
Object {
[
{
"from": "Alice",
"message": "Hello Bob, how are you?",
"to": "Bob",
"type": 5,
"wrap": false,
},
Object {
{
"from": "Bob",
"message": "I am good thanks!",
"to": "Alice",
@ -52,15 +52,15 @@ describe('more than one sequence diagram', () => {
Bob-->Alice: I am good thanks!`);
expect(diagram2.db.getMessages()).toMatchInlineSnapshot(`
Array [
Object {
[
{
"from": "Alice",
"message": "Hello Bob, how are you?",
"to": "Bob",
"type": 5,
"wrap": false,
},
Object {
{
"from": "Bob",
"message": "I am good thanks!",
"to": "Alice",
@ -77,15 +77,15 @@ describe('more than one sequence diagram', () => {
John-->Alice: I am good thanks!`);
expect(diagram3.db.getMessages()).toMatchInlineSnapshot(`
Array [
Object {
[
{
"from": "Alice",
"message": "Hello John, how are you?",
"to": "John",
"type": 5,
"wrap": false,
},
Object {
{
"from": "John",
"message": "I am good thanks!",
"to": "Alice",

View File

@ -1,5 +1,5 @@
const svgDraw = require('./svgDraw').default;
const { MockD3 } = require('d3');
import svgDraw from './svgDraw';
import { MockD3 } from 'd3';
describe('svgDraw', function () {
describe('drawRect', function () {

View File

@ -389,7 +389,7 @@ describe('state diagram, ', function () {
});
});
describe('when parsing an ignored info graph it', function () {
xit('should handle if statements', function () {
it.skip('should handle if statements', function () {
const str = `stateDiagram\n
[*] --> "Order Submitted"
if "Payment Accepted" then

View File

@ -1,4 +1,5 @@
import journeyDb from './journeyDb';
import { convert } from '../../tests/util';
describe('when using the journeyDb', function () {
beforeEach(function () {
@ -13,13 +14,13 @@ describe('when using the journeyDb', function () {
journeyDb.clear();
});
it.each`
it.each(convert`
fn | expected
${'getTasks'} | ${[]}
${'getAccTitle'} | ${''}
${'getSections'} | ${[]}
${'getActors'} | ${[]}
`('should clear $fn', ({ fn, expected }) => {
`)('should clear $fn', ({ fn, expected }) => {
expect(journeyDb[fn]()).toEqual(expected);
});
});
@ -31,18 +32,18 @@ describe('when using the journeyDb', function () {
journeyDb.addTask('test2', '1: id2');
journeyDb.clear();
});
it.each`
it.each(convert`
fn | expected
${'getTasks'} | ${[]}
${'getAccTitle'} | ${''}
${'getAccDescription'} | ${''}
${'getSections'} | ${[]}
`('should clear $fn', ({ fn, expected }) => {
`)('should clear $fn', ({ fn, expected }) => {
expect(journeyDb[fn]()).toEqual(expected);
});
});
describe('tasks and actors should be added', function () {
it('tasks and actors should be added', function () {
journeyDb.setAccTitle('Shopping');
journeyDb.setAccDescription('A user journey for family shopping');
journeyDb.addSection('Journey to the shops');

View File

@ -1405,6 +1405,15 @@ This sets the auto-wrap padding for the diagram (sides only)
**Notes:** Default value: 0.
## parse
### Parameters
- `text` **[string][5]**
- `parseError` **[Function][6]?**
Returns **[boolean][7]**
## setSiteConfig
## setSiteConfig
@ -1422,7 +1431,7 @@ function _Default value: At default, will mirror Global Config_
- `conf` **MermaidConfig** The base currentConfig to use as siteConfig
Returns **[object][5]** The siteConfig
Returns **[object][8]** The siteConfig
## getSiteConfig
@ -1434,7 +1443,7 @@ Returns **[object][5]** The siteConfig
**Notes**: Returns **any** values in siteConfig.
Returns **[object][5]** The siteConfig
Returns **[object][8]** The siteConfig
## setConfig
@ -1473,10 +1482,10 @@ $(function () {
### Parameters
- `id` **[string][6]** The id of the element to be rendered
- `text` **[string][6]** The graph definition
- `cb` **function (svgCode: [string][6], bindFunctions: function (element: [Element][7]): void): void**
- `container` **[Element][7]** Selector to element in which a div with the graph temporarily will be
- `id` **[string][5]** The id of the element to be rendered
- `text` **[string][5]** The graph definition
- `cb` **function (svgCode: [string][5], bindFunctions: function (element: [Element][9]): void): void**
- `container` **[Element][9]** Selector to element in which a div with the graph temporarily will be
inserted. If one is provided a hidden div will be inserted in the body of the page instead. The
element will be removed when rendering is completed.
@ -1515,7 +1524,7 @@ Pushes in a directive to the configuration
### Parameters
- `directive` **[object][5]** The directive to push in
- `directive` **[object][8]** The directive to push in
## reset
@ -1613,6 +1622,8 @@ Returns **void**
[2]: Setup.md?id=render
[3]: 8.6.0_docs.md
[4]: #mermaidapi-configuration-defaults
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[7]: https://developer.mozilla.org/docs/Web/API/Element
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
[7]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[9]: https://developer.mozilla.org/docs/Web/API/Element

View File

@ -1,17 +1,17 @@
import mermaid from './mermaid';
import { mermaidAPI } from './mermaidAPI';
import flowDb from './diagrams/flowchart/flowDb';
// @ts-ignore
import flowParser from './diagrams/flowchart/parser/flow';
import flowRenderer from './diagrams/flowchart/flowRenderer';
import Diagram from './Diagram';
import { vi, describe, it, beforeEach, afterEach } from 'vitest';
const spyOn = vi.spyOn;
const spyOn = jest.spyOn;
// mocks the mermaidAPI.render function (see `./__mocks__/mermaidAPI`)
jest.mock('./mermaidAPI');
vi.mock('./mermaidAPI');
afterEach(() => {
jest.restoreAllMocks();
vi.restoreAllMocks();
});
describe('when using mermaid and ', function () {
@ -70,7 +70,7 @@ describe('when using mermaid and ', function () {
const edges = diag.db.getEdges();
const mockG = {
setEdge: function (start, end, options) {
setEdge: function (start: any, end: any, options: { arrowhead: any; label: string }) {
expect(start).toContain('flowchart-A-');
expect(end).toContain('flowchart-B-');
expect(options.arrowhead).toBe('normal');
@ -87,7 +87,7 @@ describe('when using mermaid and ', function () {
const edges = diag.db.getEdges();
const mockG = {
setEdge: function (start, end, options) {
setEdge: function (start: any, end: any, options: { arrowhead: any }) {
expect(start).toContain('flowchart-A-');
expect(end).toContain('flowchart-B-');
expect(options.arrowhead).toBe('normal');
@ -103,7 +103,7 @@ describe('when using mermaid and ', function () {
const edges = diag.db.getEdges();
const mockG = {
setEdge: function (start, end, options) {
setEdge: function (start: any, end: any, options: { arrowhead: any }) {
expect(start).toContain('flowchart-A-');
expect(end).toContain('flowchart-B-');
expect(options.arrowhead).toBe('none');
@ -119,7 +119,7 @@ describe('when using mermaid and ', function () {
const edges = diag.db.getEdges();
const mockG = {
setEdge: function (start, end, options) {
setEdge: function (start: any, end: any, options: { arrowhead: any; style: any }) {
expect(start).toContain('flowchart-A-');
expect(end).toContain('flowchart-B-');
expect(options.arrowhead).toBe('none');
@ -135,7 +135,7 @@ describe('when using mermaid and ', function () {
const edges = diag.db.getEdges();
const mockG = {
setEdge: function (start, end, options) {
setEdge: function (start: any, end: any, options: { arrowhead: any; curve: any }) {
expect(start).toContain('flowchart-A-');
expect(end).toContain('flowchart-B-');
expect(options.arrowhead).toBe('none');
@ -153,7 +153,11 @@ describe('when using mermaid and ', function () {
const edges = diag.db.getEdges();
const mockG = {
setEdge: function (start, end, options) {
setEdge: function (
start: any,
end: any,
options: { arrowhead: any; label: string; style: any }
) {
expect(start).toContain('flowchart-A-');
expect(end).toContain('flowchart-B-');
expect(options.arrowhead).toBe('none');
@ -171,7 +175,7 @@ describe('when using mermaid and ', function () {
const edges = diag.db.getEdges();
const mockG = {
setEdge: function (start, end, options) {
setEdge: function (start: any, end: any, options: { arrowhead: any; style: any }) {
expect(start).toContain('flowchart-A-');
expect(end).toContain('flowchart-B');
expect(options.arrowhead).toBe('none');
@ -189,7 +193,7 @@ describe('when using mermaid and ', function () {
diag.db.getVertices();
const edges = diag.db.getEdges();
const mockG = {
setEdge: function (start, end, options) {
setEdge: function (start: any, end: any, options: { arrowhead: any; style: any }) {
expect(start).toContain('flowchart-A-');
expect(end).toContain('flowchart-B-');
expect(options.arrowhead).toBe('none');

View File

@ -39,7 +39,6 @@ import { evaluate } from './diagrams/common/common';
let hasLoadedDiagrams = false;
/**
*
* @param text
* @param parseError
*/

3
src/tests/setup.ts Normal file
View File

@ -0,0 +1,3 @@
import { vi } from 'vitest';
vi.mock('d3');
vi.mock('dagre-d3');

16
src/tests/util.ts Normal file
View File

@ -0,0 +1,16 @@
export const convert = (template: TemplateStringsArray, ...params: any[]) => {
const header = template[0]
.trim()
.split('|')
.map((s) => s.trim());
if (header.length === 0 || params.length % header.length !== 0) {
throw new Error('Table column count mismatch');
}
const chunkSize = header.length;
const out = [];
for (let i = 0; i < params.length; i += chunkSize) {
const chunk = params.slice(i, i + chunkSize);
out.push(Object.fromEntries(chunk.map((v, i) => [header[i], v])));
}
return out;
};

View File

@ -1,3 +1,4 @@
import { vi, describe, it, expect, beforeEach } from 'vitest';
import utils from './utils';
import assignWithDepth from './assignWithDepth';
import { detectType } from './diagram-api/detectType';
@ -306,14 +307,22 @@ describe('when calculating SVG size', function () {
});
describe('when initializing the id generator', function () {
it('should return a random number generator based on Date', function (done) {
beforeEach(() => {
// tell vitest we use mocked time
vi.useFakeTimers();
});
afterEach(() => {
// restoring date after each test run
vi.useRealTimers();
});
it('should return a random number generator based on Date', function () {
const idGenerator = new utils.initIdGenerator(false);
expect(typeof idGenerator.next).toEqual('function');
const lastId = idGenerator.next();
setTimeout(() => {
expect(idGenerator.next() > lastId).toBe(true);
done();
}, 5);
vi.advanceTimersByTime(1000);
expect(idGenerator.next() > lastId).toBe(true);
});
it('should return a non random number generator', function () {

View File

@ -11,8 +11,9 @@
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"target": "ES6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"lib": [
"DOM",
"ES2021"
] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
// "jsx": "preserve", /* Specify what JSX code is generated. */
@ -33,7 +34,10 @@
// "paths": {} /* Specify a set of entries that re-map imports to additional lookup locations. */,
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [] /* Specify multiple folders that act like `./node_modules/@types`. */,
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
"types": [
"vitest/globals"
] /* Specify type package names to be included without being referenced in a source file. */,
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
"resolveJsonModule": true /* Enable importing .json files */,
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
@ -100,5 +104,5 @@
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": ["./src/**/*.ts", "./package.json"]
"include": ["./src/**/*.ts", "./package.json", "src/mermaid.spec.ts"]
}

41
vite.config.ts Normal file
View File

@ -0,0 +1,41 @@
import jison from 'jison';
import { defineConfig } from 'vitest/config';
const fileRegex = /\.(jison)$/;
/** Transforms jison to js. */
export function jisonPlugin() {
return {
name: 'transform-jison',
transform(src: string, id: string) {
if (fileRegex.test(id)) {
return {
// @ts-ignore
code: new jison.Generator(src, { 'token-stack': true }).generate(),
map: null, // provide source map if available
};
}
},
};
}
export default defineConfig({
resolve: {
extensions: ['.jison', '.js', '.ts', '.json'],
},
plugins: [jisonPlugin()],
test: {
// coverage: {
// enabled: true,
// },
environment: 'jsdom',
globals: true,
mockReset: true,
clearMocks: true,
deps: {
inline: ['dagre-d3', 'd3'],
},
setupFiles: ['src/tests/setup.ts'],
},
});

1534
yarn.lock

File diff suppressed because it is too large Load Diff