mocha#after TypeScript Examples
The following examples show how to use
mocha#after.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: extension.test.ts From vscode-code-review with MIT License | 6 votes |
// import * as myExtension from '../extension';
suite('Extension Test Suite', () => {
after(() => {
vscode.window.showInformationMessage('All tests done!');
});
test('Sample test', () => {
assert.strictEqual(-1, [1, 2, 3].indexOf(5));
assert.strictEqual(-1, [1, 2, 3].indexOf(0));
});
});
Example #2
Source File: extension.test.ts From vscode-riscv-venus with MIT License | 6 votes |
// import * as myExtension from '../extension';
suite('Extension Test Suite', () => {
after(() => {
vscode.window.showInformationMessage('All tests done!');
});
test('Sample test', () => {
assert.strictEqual(0, [1, 2, 3].indexOf(1));
assert.strictEqual(1, [1, 2, 3].indexOf(2));
});
});
Example #3
Source File: ChangeWorkspace.test.ts From dendron with GNU Affero General Public License v3.0 | 5 votes |
// eslint-disable-next-line prefer-arrow-callback
suite("GIVEN ChangeWorkspace command", function () {
describeMultiWS("WHEN command is gathering inputs", {}, () => {
let showOpenDialog: sinon.SinonStub;
beforeEach(async () => {
const cmd = new ChangeWorkspaceCommand();
showOpenDialog = sinon.stub(window, "showOpenDialog");
await cmd.gatherInputs();
});
afterEach(() => {
showOpenDialog.restore();
});
test("THEN file picker is opened", (done) => {
expect(showOpenDialog.calledOnce).toBeTruthy();
done();
});
});
describeMultiWS("WHEN command is run", {}, (ctx) => {
describe("AND a code workspace is selected", () => {
let openWS: sinon.SinonStub;
let newWSRoot: string;
before(async () => {
const { wsRoot: currentWSRoot } = getDWorkspace();
openWS = sinon.stub(VSCodeUtils, "openWS").resolves();
const out = await setupLegacyWorkspaceMulti({
ctx,
workspaceType: WorkspaceType.CODE,
});
newWSRoot = out.wsRoot;
expect(newWSRoot).toNotEqual(currentWSRoot);
const cmd = new ChangeWorkspaceCommand();
sinon.stub(cmd, "gatherInputs").resolves({ rootDirRaw: newWSRoot });
await cmd.run();
});
after(() => {
openWS.restore();
});
test("THEN workspace is opened", (done) => {
expect(openWS.calledOnce).toBeTruthy();
expect(openWS.calledOnceWithExactly(newWSRoot));
done();
});
});
describe("AND a native workspace is selected", () => {
let openWS: sinon.SinonStub;
let newWSRoot: string;
before(async () => {
const { wsRoot: currentWSRoot } = getDWorkspace();
openWS = sinon.stub(VSCodeUtils, "openWS").resolves();
const out = await setupLegacyWorkspaceMulti({
ctx,
workspaceType: WorkspaceType.NATIVE,
});
newWSRoot = out.wsRoot;
expect(newWSRoot).toNotEqual(currentWSRoot);
const cmd = new ChangeWorkspaceCommand();
sinon.stub(cmd, "gatherInputs").resolves({ rootDirRaw: newWSRoot });
await cmd.run();
});
after(() => {
openWS.restore();
});
test("THEN workspace is opened", (done) => {
expect(openWS.calledOnce).toBeTruthy();
expect(openWS.calledOnceWithExactly(newWSRoot));
done();
});
});
});
});
Example #4
Source File: Extension-PostInstall.test.ts From dendron with GNU Affero General Public License v3.0 | 5 votes |
suite("GIVEN keybindings conflict", function () {
let promptSpy: SinonSpy;
let installStatusStub: SinonStub;
describeMultiWS(
"GIVEN initial install",
{
beforeHook: async () => {
installStatusStub = sinon
.stub(VSCodeUtils, "getInstallStatusForExtension")
.returns(InstallStatus.INITIAL_INSTALL);
promptSpy = sinon.spy(KeybindingUtils, "maybePromptKeybindingConflict");
},
noSetInstallStatus: true,
},
() => {
beforeEach(() => {
installStatusStub = sinon
.stub(
KeybindingUtils,
"getInstallStatusForKnownConflictingExtensions"
)
.returns([{ id: "dummyExt", installed: true }]);
});
afterEach(() => {
installStatusStub.restore();
});
after(() => {
promptSpy.restore();
});
test("THEN maybePromptKeybindingConflict is called", async () => {
expect(promptSpy.called).toBeTruthy();
});
}
);
describeMultiWS(
"GIVEN not initial install",
{
beforeHook: async () => {
promptSpy = sinon.spy(KeybindingUtils, "maybePromptKeybindingConflict");
},
},
() => {
beforeEach(() => {
installStatusStub = sinon
.stub(
KeybindingUtils,
"getInstallStatusForKnownConflictingExtensions"
)
.returns([{ id: "dummyExt", installed: true }]);
});
afterEach(() => {
installStatusStub.restore();
});
after(() => {
promptSpy.restore();
});
test("THEN maybePromptKeybindingConflict is not called", async () => {
expect(promptSpy.called).toBeFalsy();
});
}
);
});
Example #5
Source File: analytics.test.ts From dendron with GNU Affero General Public License v3.0 | 5 votes |
describe("GIVEN AnalyticsUtils", () => {
describe("WHEN getSessionId called twice", () => {
test("THEN get same value", () => {
const val1 = AnalyticsUtils.getSessionId();
const val2 = AnalyticsUtils.getSessionId();
expect(val1).toNotEqual(-1);
expect(val1).toEqual(val2);
});
});
describe("WHEN trackForNextRun is used", () => {
const event = "TestEventOccurred";
const numbers = [1, 1, 2, 3, 5, 8];
const namesYears = {
"Jeffrey David Ullman": 2020,
"Jack Dongarra": 2021,
};
let homedir: string;
before(async () => {
homedir = tmpDir().name;
sinon.stub(os, "homedir").returns(homedir);
await AnalyticsUtils.trackForNextRun(event, {
numbers,
namesYears,
});
});
after(() => {
sinon.restore();
});
test("THEN the properties are saved to disk", async () => {
const telemetryDir = path.join(
homedir,
FOLDERS.DENDRON_SYSTEM_ROOT,
FOLDERS.SAVED_TELEMETRY
);
const savedFiles = (await fs.readdir(telemetryDir)).filter(
(filename) => path.extname(filename) === ".json"
);
expect(savedFiles.length).toEqual(1);
const contents = await fs.readFile(
path.join(telemetryDir, savedFiles[0]),
{ encoding: "utf-8" }
);
expect(contents.includes(event)).toBeTruthy();
expect(contents.includes("5")).toBeTruthy();
expect(contents.includes("8")).toBeTruthy();
expect(contents.includes("Jeffrey David Ullman")).toBeTruthy();
expect(contents.includes("Jack Dongarra")).toBeTruthy();
expect(contents.includes("timestamp")).toBeTruthy();
});
describe("AND when sendSavedAnalytics is used", () => {
let trackStub: sinon.SinonStub<
Parameters<typeof SegmentUtils["trackSync"]>
>;
before(async () => {
trackStub = sinon.stub(SegmentUtils, "trackSync");
await AnalyticsUtils.sendSavedAnalytics();
});
after(() => {
trackStub.restore();
});
test("THEN the saved event is sent", async () => {
expect(trackStub.calledOnce).toBeTruthy();
const args = trackStub.args[0][0];
// Should be the right event
expect(args.event).toEqual(event);
// All the props should match
expect(_.isEqual(args.properties?.numbers, numbers)).toBeTruthy();
expect(_.isEqual(args.properties?.namesYears, namesYears)).toBeTruthy();
// Timestamp should be serialzed and saved, then parsed on load
expect(args.timestamp instanceof Date).toBeTruthy();
});
});
});
});
Example #6
Source File: testUtilsV3.ts From dendron with GNU Affero General Public License v3.0 | 5 votes |
/**
* Use to run tests with a single-vault workspace. Used in the same way as
* regular `describe`.
* @param title
* @param opts
* @param fn - the test() functions to execute. NOTE: This function CANNOT be
* async, or else the test may not fail reliably when your expect or assert
* conditions are not met.
*/
export function describeSingleWS(
title: string,
opts: SetupLegacyWorkspaceOpts & {
/**
* Custom timeout for test in milleseconds
* You will need to set this when stepping through mocha tests using breakpoints
* otherwise the test will timeout during debugging
* See [[Breakpoints|dendron://dendron.docs/pkg.plugin-core.qa.debug#breakpoints]] for more details
*/
timeout?: number;
},
fn: (ctx: ExtensionContext) => void
) {
describe(title, function () {
if (opts.timeout) {
this.timeout(opts.timeout);
}
const ctx = opts.ctx ?? VSCodeUtils.getOrCreateMockContext();
before(async () => {
setupWorkspaceStubs({ ...opts, ctx });
await setupLegacyWorkspace(opts);
await _activate(ctx);
});
const result = fn(ctx);
assertTestFnNotAsync(result);
// Release all registered resouces such as commands and providers
after(() => {
cleanupWorkspaceStubs(ctx);
});
});
}
Example #7
Source File: EngineNoteProvider.test.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
/**
* Tests the EngineNoteProvider
*/
suite("EngineNoteProvider Tests", function testSuite() {
// Set test timeout to 2 seconds
this.timeout(2000);
describe("general", function () {
const ctx: vscode.ExtensionContext = setupBeforeAfter(this, {});
describe(`WHEN a note has been created`, function () {
test("THEN the data provider refresh event gets invoked", (done) => {
runLegacyMultiWorkspaceTest({
ctx,
postSetupHook: ENGINE_HOOKS_MULTI.setupBasicMulti,
onInit: async ({ vaults, wsRoot }) => {
const testNoteProps = await NoteTestUtilsV4.createNote({
fname: "alpha",
vault: vaults[0],
wsRoot,
});
const mockEvents = new MockEngineEvents();
const provider = new EngineNoteProvider(mockEvents);
provider.onDidChangeTreeData(() => {
done();
});
const entry: NoteChangeEntry = {
note: testNoteProps,
status: "create",
};
mockEvents.testFireOnNoteChanged([entry]);
},
});
});
});
describe(`WHEN a note has been updated`, function () {
test("THEN the data provider refresh event gets invoked", (done) => {
runLegacyMultiWorkspaceTest({
ctx,
postSetupHook: ENGINE_HOOKS_MULTI.setupBasicMulti,
onInit: async ({ vaults, wsRoot }) => {
const testNoteProps = await NoteTestUtilsV4.createNote({
fname: "alpha",
vault: vaults[0],
wsRoot,
});
const mockEvents = new MockEngineEvents();
const provider = new EngineNoteProvider(mockEvents);
provider.onDidChangeTreeData(() => {
done();
});
const entry: NoteChangeEntry = {
prevNote: testNoteProps,
note: testNoteProps,
status: "update",
};
mockEvents.testFireOnNoteChanged([entry]);
},
});
});
});
describe(`WHEN a note has been deleted`, function () {
test("THEN the data provider refresh event gets invoked", (done) => {
runLegacyMultiWorkspaceTest({
ctx,
postSetupHook: ENGINE_HOOKS_MULTI.setupBasicMulti,
onInit: async ({ vaults, wsRoot }) => {
const testNoteProps = await NoteTestUtilsV4.createNote({
fname: "alpha",
vault: vaults[0],
wsRoot,
});
const mockEvents = new MockEngineEvents();
const provider = new EngineNoteProvider(mockEvents);
provider.onDidChangeTreeData(() => {
done();
});
const entry: NoteChangeEntry = {
note: testNoteProps,
status: "delete",
};
mockEvents.testFireOnNoteChanged([entry]);
},
});
});
});
});
describe("tree data", function () {
const preSetupHookFunc = async (opts: WorkspaceOpts & { extra?: any }) => {
const { vaults, wsRoot } = opts;
const vault = vaults[0];
await NOTE_PRESETS_V4.NOTE_WITH_LOWER_CASE_TITLE.create({
wsRoot,
vault,
});
await NOTE_PRESETS_V4.NOTE_WITH_UPPER_CASE_TITLE.create({
wsRoot,
vault,
});
await NOTE_PRESETS_V4.NOTE_WITH_UNDERSCORE_TITLE.create({
wsRoot,
vault,
});
await NoteTestUtilsV4.createNote({
wsRoot,
vault: vaults[0],
fname: "zebra",
custom: {
nav_order: 1,
},
});
};
describe("sort / label config", function () {
describeMultiWS(
"WHEN treeViewItemLabelType is omitted",
{
preSetupHook: async (opts) => {
await preSetupHookFunc(opts);
MetadataService.instance().deleteMeta("treeViewItemLabelType");
},
},
() => {
test("THEN label and sort tree items by title", async () => {
expect(
MetadataService.instance().getTreeViewItemLabelType()
).toEqual(TreeViewItemLabelTypeEnum.title);
const mockEvents = new MockEngineEvents();
const provider = new EngineNoteProvider(mockEvents);
const props = await (provider.getChildren() as Promise<
NoteProps[]
>);
const vault1RootProps = props[0];
const children = await provider.getChildren(vault1RootProps);
expect(children?.map((child) => child.title)).toEqual([
"Zebra", // nav_order: 1
"Aardvark", // uppercase alphabets comes before underscore alphabets
"_underscore", // underscore comes before lowercase alphabets
"aaron",
]);
});
}
);
describeMultiWS(
"WHEN treeViewItemLabelType is title",
{
preSetupHook: async (opts) => {
await preSetupHookFunc(opts);
MetadataService.instance().setTreeViewItemLabelType(
TreeViewItemLabelTypeEnum.title
);
},
},
() => {
after(() => {
MetadataService.instance().deleteMeta("treeViewItemLabelType");
});
test("THEN label and sort tree items by title", async () => {
const mockEvents = new MockEngineEvents();
const provider = new EngineNoteProvider(mockEvents);
const props = await (provider.getChildren() as Promise<
NoteProps[]
>);
const vault1RootProps = props[0];
const children = await provider.getChildren(vault1RootProps);
expect(children?.map((child) => child.title)).toEqual([
"Zebra", // nav_order: 1
"Aardvark", // uppercase alphabets comes before underscore alphabets
"_underscore", // underscore comes before lowercase alphabets
"aaron",
]);
});
}
);
describeMultiWS(
"WHEN treeViewItemLabelType is filename",
{
preSetupHook: async (opts) => {
await preSetupHookFunc(opts);
MetadataService.instance().setTreeViewItemLabelType(
TreeViewItemLabelTypeEnum.filename
);
},
},
() => {
after(() => {
MetadataService.instance().deleteMeta("treeViewItemLabelType");
});
test("THEN label and sort tree items by filename", async () => {
const mockEvents = new MockEngineEvents();
const provider = new EngineNoteProvider(mockEvents);
const props = await (provider.getChildren() as Promise<
NoteProps[]
>);
const vault1RootProps = props[0];
const children = await provider.getChildren(vault1RootProps);
expect(
children?.map((child) => _.last(child.fname.split(".")))
).toEqual([
"zebra", // nav_order: 1
"_underscore", // underscore comes before lowercase alphabets
"aardvark",
"aaron",
]);
});
}
);
});
describeMultiWS(
"WHEN the engine note provider is providing tree data on the root node",
{
postSetupHook: ENGINE_HOOKS_MULTI.setupBasicMulti,
},
() => {
test("THEN the tree data is correct", async () => {
const mockEvents = new MockEngineEvents();
const provider = new EngineNoteProvider(mockEvents);
const props = await (provider.getChildren() as Promise<NoteProps[]>);
// 3 Vaults hence 3 root nodes
expect(props.length === 3);
// Also check some children:
props.forEach((props) => {
switch (props.vault.fsPath) {
case "vault1": {
if (
props.children.length !== 1 ||
props.children[0] !== "foo"
) {
throw new DendronError({
message: "Note children in vault1 incorrect!",
});
}
break;
}
case "vault2": {
if (
props.children.length !== 1 ||
props.children[0] !== "bar"
) {
throw new DendronError({
message: "Note children in vault2 incorrect!",
});
}
break;
}
case "vault3": {
if (props.children.length !== 0) {
throw new DendronError({
message: "Note children in vault3 incorrect!",
});
}
break;
}
default: {
throw new DendronError({
message: "Note with unexpected vault found!",
});
}
}
});
});
}
);
describe("WHEN the engine note provider is providing tree data on the root node with children", function () {
describeMultiWS(
"AND tags hierarchy doesn't specify nav_order",
{
preSetupHook: async (opts) => {
const { vaults, wsRoot } = opts;
const vault = vaults[0];
await preSetupHookFunc(opts);
await NoteTestUtilsV4.createNote({
wsRoot,
vault,
fname: "tags.aa-battery",
});
},
},
() => {
test("THEN tree item sort order is correct", async () => {
const mockEvents = new MockEngineEvents();
const provider = new EngineNoteProvider(mockEvents);
const props = await (provider.getChildren() as Promise<
NoteProps[]
>);
const vault1RootProps = props[0];
const children = await provider.getChildren(vault1RootProps);
expect(children?.map((child) => child.title)).toEqual([
"Zebra", // nav_order: 1
"Aardvark", // uppercase alphabets comes before underscore alphabets
"_underscore", // underscore comes before lowercase alphabets
"aaron",
"Tags", // tags come last.
]);
});
}
);
describeMultiWS(
"AND tags hierarchy doesn't specify nav_order",
{
preSetupHook: async (opts) => {
const { wsRoot, vaults } = opts;
await preSetupHookFunc(opts);
await NoteTestUtilsV4.createNote({
wsRoot,
vault: vaults[0],
fname: "tags",
custom: {
nav_order: 1.2,
},
});
await NoteTestUtilsV4.createNote({
wsRoot,
vault: vaults[0],
fname: "tags.aa-battery",
});
},
},
() => {
test("THEN tag hierarchy nav_order is respected", async () => {
const mockEvents = new MockEngineEvents();
const provider = new EngineNoteProvider(mockEvents);
const props = await (provider.getChildren() as Promise<
NoteProps[]
>);
const vault1RootProps = props[0];
const children = await provider.getChildren(vault1RootProps);
expect(children?.map((child) => child.title)).toEqual([
"Zebra", // nav_order: 1
"Tags", // nav_order respected
"Aardvark", // uppercase alphabets comes before underscore alphabets
"_underscore", // underscore comes before lowercase alphabets
"aaron",
]);
});
}
);
});
});
});
Example #8
Source File: MigrateSelfContainedVault.test.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
suite("GIVEN the MigrateSelfContainedVault command", () => {
describeSingleWS(
"WHEN the vault prompt is cancelled",
{ selfContained: false },
() => {
let showErrorMessage: SinonStubbedFn<typeof window["showErrorMessage"]>;
let reloadWindow: SinonStubbedFn<typeof VSCodeUtils["reloadWindow"]>;
let showQuickPick: SinonStubbedFn<typeof VSCodeUtils["showQuickPick"]>;
before(async () => {
const cmd = new MigrateSelfContainedVaultCommand(
ExtensionProvider.getExtension()
);
showErrorMessage = sinon.stub(window, "showErrorMessage");
reloadWindow = sinon.stub(VSCodeUtils, "reloadWindow");
showQuickPick = sinon
.stub(VSCodeUtils, "showQuickPick")
.resolves(undefined);
await cmd.run();
});
after(() => {
[showErrorMessage, reloadWindow, showQuickPick].forEach((stub) =>
stub.restore()
);
});
test("THEN the workspace did not reload since there was no migration", () => {
expect(reloadWindow.called).toBeFalsy();
});
test("THEN the vault should not have migrated", async () => {
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
expect(
await verifyVaultNotMigrated({ wsRoot, vault: vaults[0] })
).toBeTruthy();
});
}
);
describeSingleWS(
"WHEN the backup prompt is cancelled",
{ selfContained: false },
() => {
let showErrorMessage: SinonStubbedFn<typeof window["showErrorMessage"]>;
let reloadWindow: SinonStubbedFn<typeof VSCodeUtils["reloadWindow"]>;
let showQuickPick: SinonStubbedFn<typeof VSCodeUtils["showQuickPick"]>;
before(async () => {
const cmd = new MigrateSelfContainedVaultCommand(
ExtensionProvider.getExtension()
);
showErrorMessage = sinon.stub(window, "showErrorMessage");
reloadWindow = sinon.stub(VSCodeUtils, "reloadWindow");
const { vaults } = ExtensionProvider.getDWorkspace();
showQuickPick = stubMigrateQuickPick(
VaultUtils.getName(vaults[0]),
MigrateVaultContinueOption.cancel
);
await cmd.run();
});
after(() => {
[showErrorMessage, reloadWindow, showQuickPick].forEach((stub) =>
stub.restore()
);
});
test("THEN the workspace did not reload since there was no migration", () => {
expect(reloadWindow.called).toBeFalsy();
});
test("THEN the vault should not have migrated", async () => {
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
expect(
await verifyVaultNotMigrated({ wsRoot, vault: vaults[0] })
).toBeTruthy();
});
}
);
describeSingleWS(
"WHEN there's only a single vault, and it's self contained",
{ selfContained: true },
() => {
let showErrorMessage: SinonStubbedFn<typeof window["showErrorMessage"]>;
let reloadWindow: SinonStubbedFn<typeof VSCodeUtils["reloadWindow"]>;
let showQuickPick: SinonStubbedFn<typeof VSCodeUtils["showQuickPick"]>;
before(async () => {
const cmd = new MigrateSelfContainedVaultCommand(
ExtensionProvider.getExtension()
);
showErrorMessage = sinon.stub(window, "showErrorMessage");
reloadWindow = sinon.stub(VSCodeUtils, "reloadWindow");
showQuickPick = sinon.stub(VSCodeUtils, "showQuickPick");
await cmd.run();
});
after(() => {
[showErrorMessage, reloadWindow, showQuickPick].forEach((stub) =>
stub.restore()
);
});
test("THEN there's an error that there's nothing to migrate", () => {
expect(showErrorMessage.calledOnce).toBeTruthy();
expect(showErrorMessage.args[0][0].includes("no vault")).toBeTruthy();
});
test("THEN no vault is prompted for", () => {
expect(showQuickPick.called).toBeFalsy();
});
test("THEN the workspace did not reload since there was no migration", () => {
expect(reloadWindow.called).toBeFalsy();
});
}
);
describeSingleWS(
"WHEN there's only a single vault, and it's not self contained",
{
selfContained: false,
modConfigCb: (config) => {
const vault = ConfigUtils.getVaults(config)[0];
// Using an asset in the vault as the logo. Migration should update the path.
ConfigUtils.setPublishProp(
config,
"logoPath",
`${vault.fsPath}/assets/image.png`
);
return config;
},
postSetupHook: async ({ wsRoot, vaults }) => {
const vaultPath = pathForVaultRoot({ wsRoot, vault: vaults[0] });
// Mock git folder & files to see if migration handles them.
await fs.ensureDir(path.join(vaultPath, ".git"));
await fs.writeFile(path.join(vaultPath, ".gitignore"), "");
// Also mock the logo file
await fs.ensureDir(path.join(vaultPath, "assets"));
await fs.writeFile(path.join(vaultPath, "assets", "image.png"), "");
},
},
() => {
let reloadWindow: SinonStubbedFn<typeof VSCodeUtils["reloadWindow"]>;
let showQuickPick: SinonStubbedFn<typeof VSCodeUtils["showQuickPick"]>;
before(async () => {
const { vaults } = ExtensionProvider.getDWorkspace();
const cmd = new MigrateSelfContainedVaultCommand(
ExtensionProvider.getExtension()
);
reloadWindow = sinon.stub(VSCodeUtils, "reloadWindow");
showQuickPick = stubMigrateQuickPick(VaultUtils.getName(vaults[0]));
await cmd.run();
});
after(() => {
[reloadWindow, showQuickPick].forEach((stub) => stub.restore());
});
test("THEN it prompts for the vault and confirmation", () => {
expect(showQuickPick.callCount).toEqual(2);
});
test("THEN the workspace reloads to apply the migration", () => {
expect(reloadWindow.called).toBeTruthy();
});
test("THEN the vault is migrated", async () => {
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
expect(
verifyVaultHasMigrated({ wsRoot, vault: vaults[0] })
).toBeTruthy();
});
test("THEN the logoPath is updated to account for the moved asset", async () => {
const { wsRoot, config } = ExtensionProvider.getDWorkspace();
const logoPath = ConfigUtils.getPublishing(config).logoPath;
expect(logoPath).toBeTruthy();
// If the logoPath was not updated, then we won't find the asset file there
expect(
await fs.pathExists(path.join(wsRoot, path.normalize(logoPath!)))
).toBeTruthy();
});
test("THEN the git folders/files are handled correctly", async () => {
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
expect(
await fs.pathExists(
path.join(pathForVaultRoot({ vault: vaults[0], wsRoot }), ".git")
)
).toBeTruthy();
expect(
await fs.pathExists(
path.join(
pathForVaultRoot({ vault: vaults[0], wsRoot }),
".gitignore"
)
)
).toBeTruthy();
});
}
);
describeMultiWS(
"WHEN there are multiple vaults",
{ selfContained: false },
() => {
let reloadWindow: SinonStubbedFn<typeof VSCodeUtils["reloadWindow"]>;
let showQuickPick: SinonStubbedFn<typeof VSCodeUtils["showQuickPick"]>;
before(async () => {
const { vaults } = ExtensionProvider.getDWorkspace();
const cmd = new MigrateSelfContainedVaultCommand(
ExtensionProvider.getExtension()
);
reloadWindow = sinon.stub(VSCodeUtils, "reloadWindow");
showQuickPick = stubMigrateQuickPick(VaultUtils.getName(vaults[0]));
await cmd.run();
});
after(() => {
[reloadWindow, showQuickPick].forEach((stub) => stub.restore());
});
test("THEN it prompts for the vault and confirmation", () => {
expect(showQuickPick.callCount).toEqual(2);
});
test("THEN the workspace reloads to apply the migration", () => {
expect(reloadWindow.called).toBeTruthy();
});
test("THEN the vault is migrated", async () => {
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
expect(
verifyVaultHasMigrated({ wsRoot, vault: vaults[0] })
).toBeTruthy();
});
}
);
});
Example #9
Source File: Survey.test.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
suite("SurveyUtils", function () {
describe("showInitialSurvey", () => {
let homeDirStub: SinonStub;
let stateStub: SinonStub;
let surveySpy: SinonSpy;
describeMultiWS(
"GIVEN INITIAL_SURVEY_SUBMITTED is not set",
{
beforeHook: async () => {
await resetCodeWorkspace();
homeDirStub = TestEngineUtils.mockHomeDir();
},
},
() => {
after(() => {
homeDirStub.restore();
});
beforeEach(() => {
stateStub = sinon
.stub(StateService.instance(), "getGlobalState")
.resolves(undefined);
surveySpy = sinon.spy(SurveyUtils, "showInitialSurvey");
});
afterEach(() => {
stateStub.restore();
surveySpy.restore();
});
describe("AND initialSurveyStatus is not set", () => {
test("THEN showInitialSurvey is called", async () => {
const tutorialInitializer = new TutorialInitializer();
const ws = ExtensionProvider.getDWorkspace();
expect(
MetadataService.instance().getMeta().initialSurveyStatus
).toEqual(undefined);
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.INITIAL_SURVEY_SUBMITTED
)
).toEqual(undefined);
await tutorialInitializer.onWorkspaceOpen({ ws });
expect(surveySpy.calledOnce).toBeTruthy();
});
});
describe("AND initialSurveyStatus is set to cancelled", () => {
test("THEN showInitialSurvey is called", async () => {
const tutorialInitializer = new TutorialInitializer();
const ws = ExtensionProvider.getDWorkspace();
MetadataService.instance().setInitialSurveyStatus(
InitialSurveyStatusEnum.cancelled
);
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.INITIAL_SURVEY_SUBMITTED
)
).toEqual(undefined);
await tutorialInitializer.onWorkspaceOpen({ ws });
expect(surveySpy.calledOnce).toBeTruthy();
});
});
describe("AND initialSurveyStatus is set to submitted", () => {
test("THEN showInitialSurvey is not called", async () => {
const tutorialInitializer = new TutorialInitializer();
const ws = ExtensionProvider.getDWorkspace();
MetadataService.instance().setInitialSurveyStatus(
InitialSurveyStatusEnum.submitted
);
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.INITIAL_SURVEY_SUBMITTED
)
).toEqual(undefined);
await tutorialInitializer.onWorkspaceOpen({ ws });
expect(surveySpy.calledOnce).toBeFalsy();
});
});
}
);
describeMultiWS(
"GIVEN INITIAL_SURVEY_SUBMITTED is set",
{
beforeHook: async () => {
await resetCodeWorkspace();
homeDirStub = TestEngineUtils.mockHomeDir();
},
},
() => {
after(() => {
homeDirStub.restore();
});
beforeEach(() => {
stateStub = sinon
.stub(StateService.instance(), "getGlobalState")
.resolves("submitted");
surveySpy = sinon.spy(SurveyUtils, "showInitialSurvey");
});
afterEach(() => {
stateStub.restore();
surveySpy.restore();
});
describe("AND initialSurveyStatus is not set", () => {
test("THEN metadata is backfilled AND showInitialSurvey is not called", async () => {
const tutorialInitializer = new TutorialInitializer();
const ws = ExtensionProvider.getDWorkspace();
// metadata is not set yet, we expect this to be backfilled
expect(
MetadataService.instance().getMeta().initialSurveyStatus
).toEqual(undefined);
// global state is already set.
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.INITIAL_SURVEY_SUBMITTED
)
).toEqual("submitted");
await tutorialInitializer.onWorkspaceOpen({ ws });
expect(surveySpy.calledOnce).toBeFalsy();
// metadata is backfilled.
expect(
MetadataService.instance().getMeta().initialSurveyStatus
).toEqual(InitialSurveyStatusEnum.submitted);
});
});
describe("AND initialSurveyStatus is set to submitted", () => {
test("THEN showInitialSurvey is not called", async () => {
const tutorialInitializer = new TutorialInitializer();
const ws = ExtensionProvider.getDWorkspace();
MetadataService.instance().setInitialSurveyStatus(
InitialSurveyStatusEnum.submitted
);
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.INITIAL_SURVEY_SUBMITTED
)
).toEqual("submitted");
await tutorialInitializer.onWorkspaceOpen({ ws });
expect(surveySpy.calledOnce).toBeFalsy();
});
});
}
);
});
describe("showLapsedUserSurvey", () => {
let homeDirStub: SinonStub;
let stateStub: SinonStub;
let surveySpy: SinonSpy;
let infoMsgStub: SinonStub;
describeMultiWS(
"GIVEN LAPSED_USER_SURVEY_SUBMITTED is not set",
{
beforeHook: async () => {
await resetCodeWorkspace();
homeDirStub = TestEngineUtils.mockHomeDir();
},
},
(ctx) => {
after(() => {
homeDirStub.restore();
});
beforeEach(() => {
stateStub = sinon
.stub(StateService.instance(), "getGlobalState")
.resolves(undefined);
surveySpy = sinon.spy(SurveyUtils, "showLapsedUserSurvey");
infoMsgStub = sinon
.stub(vscode.window, "showInformationMessage")
.resolves({ title: "foo" });
});
afterEach(() => {
stateStub.restore();
surveySpy.restore();
infoMsgStub.restore();
});
describe("AND lapsedUserSurveyStatus is not set", () => {
test("THEN showLapsedUserSurvey is called", async () => {
await StartupUtils.showLapsedUserMessage(
VSCodeUtils.getAssetUri(ctx)
);
await new Promise((resolve: any) => {
setTimeout(() => {
resolve();
}, 1);
});
expect(surveySpy.calledOnce).toBeTruthy();
});
});
describe("AND lapsedUserSurveyStatus is set to submitted", () => {
test("THEN showLapsedUserSurvey is not called", async () => {
MetadataService.instance().setLapsedUserSurveyStatus(
LapsedUserSurveyStatusEnum.submitted
);
await StartupUtils.showLapsedUserMessage(
VSCodeUtils.getAssetUri(ctx)
);
await new Promise((resolve: any) => {
setTimeout(() => {
resolve();
}, 1);
});
expect(surveySpy.calledOnce).toBeFalsy();
});
});
}
);
describeMultiWS(
"GIVEN LAPSED_USER_SURVEY_SUBMITTED is set",
{
beforeHook: async () => {
await resetCodeWorkspace();
homeDirStub = TestEngineUtils.mockHomeDir();
},
},
(ctx) => {
after(() => {
homeDirStub.restore();
});
beforeEach(() => {
stateStub = sinon
.stub(StateService.instance(), "getGlobalState")
.resolves("submitted");
surveySpy = sinon.spy(SurveyUtils, "showLapsedUserSurvey");
infoMsgStub = sinon
.stub(vscode.window, "showInformationMessage")
.resolves({ title: "foo" });
});
afterEach(() => {
stateStub.restore();
surveySpy.restore();
infoMsgStub.restore();
});
describe("AND lapsedUserSurveyStatus is not set", () => {
test("THEN metadata is backfilled AND showLapsedUserSurvye is not called", async () => {
// metadata is not set yet, we expect this to be backfilled.
expect(
MetadataService.instance().getLapsedUserSurveyStatus()
).toEqual(undefined);
// global state is already set.
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.LAPSED_USER_SURVEY_SUBMITTED
)
).toEqual("submitted");
await StartupUtils.showLapsedUserMessage(
VSCodeUtils.getAssetUri(ctx)
);
await new Promise((resolve: any) => {
setTimeout(() => {
resolve();
}, 1);
});
expect(surveySpy.calledOnce).toBeFalsy();
// metadata is backfilled.
expect(
MetadataService.instance().getLapsedUserSurveyStatus()
).toEqual(LapsedUserSurveyStatusEnum.submitted);
});
});
describe("AND lapsedUserSurveyStatus is set to submitted", () => {
test("THEN showLapsedUserSurvey is not called", async () => {
expect(
MetadataService.instance().getLapsedUserSurveyStatus()
).toEqual(LapsedUserSurveyStatusEnum.submitted);
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.LAPSED_USER_SURVEY_SUBMITTED
)
).toEqual("submitted");
await StartupUtils.showLapsedUserMessage(
VSCodeUtils.getAssetUri(ctx)
);
await new Promise((resolve: any) => {
setTimeout(() => {
resolve();
}, 1);
});
expect(surveySpy.calledOnce).toBeFalsy();
});
});
}
);
});
});
Example #10
Source File: VaultConvert.test.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
suite("GIVEN VaultConvert", function () {
describeMultiWS(
"WHEN converting a local vault to a remote vault",
{ preSetupHook: ENGINE_HOOKS_MULTI.setupBasicMulti },
() => {
let remote: string;
before(async () => {
const { vaults } = ExtensionProvider.getDWorkspace();
const cmd = new VaultConvertCommand();
sinon.stub(cmd, "gatherType").resolves("remote");
sinon.stub(cmd, "gatherVault").resolves(vaults[0]);
// Create a remote repository to be the upstream
remote = tmpDir().name;
await GitTestUtils.remoteCreate(remote);
sinon.stub(cmd, "gatherRemoteURL").resolves(remote);
await cmd.run();
});
after(async () => {
sinon.restore();
});
test("THEN updates .gitignore", async () => {
const { wsRoot } = ExtensionProvider.getDWorkspace();
const contents = await fs.readFile(path.join(wsRoot, ".gitignore"), {
encoding: "utf-8",
});
expect(contents.match(/^vault1$/m)).toBeTruthy();
});
test("THEN updates config", async () => {
const { wsRoot } = ExtensionProvider.getDWorkspace();
const config = DConfig.getRaw(wsRoot) as IntermediateDendronConfig;
expect(ConfigUtils.getVaults(config)[0].remote).toEqual({
type: "git",
url: remote,
});
});
test("THEN the folder is a git repository", async () => {
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
const git = new Git({ localUrl: path.join(wsRoot, vaults[0].fsPath) });
expect(await git.getRemote()).toEqual("origin");
expect(await git.getCurrentBranch()).toBeTruthy();
});
describe("AND converting that back to a local vault", () => {
before(async () => {
const { vaults } = ExtensionProvider.getDWorkspace();
const cmd = new VaultConvertCommand();
sinon.stub(cmd, "gatherType").resolves("local");
sinon.stub(cmd, "gatherVault").resolves(vaults[0]);
await cmd.run();
});
after(async () => {
sinon.restore();
});
test("THEN updates .gitignore", async () => {
const { wsRoot } = ExtensionProvider.getDWorkspace();
const contents = await fs.readFile(path.join(wsRoot, ".gitignore"), {
encoding: "utf-8",
});
expect(contents.match(/^vault1$/m)).toBeFalsy();
});
test("THEN updates config", async () => {
const { wsRoot } = ExtensionProvider.getDWorkspace();
const config = DConfig.getRaw(wsRoot) as IntermediateDendronConfig;
expect(ConfigUtils.getVaults(config)[0].remote).toBeFalsy();
});
test("THEN the folder is NOT a git repository", async () => {
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
const git = new Git({
localUrl: path.join(wsRoot, vaults[0].fsPath),
});
expect(await git.getRemote()).toBeFalsy();
});
});
}
);
describeMultiWS(
"WHEN converting a local vault to a remote vault with self contained vaults enabled",
{
preSetupHook: ENGINE_HOOKS_MULTI.setupBasicMulti,
modConfigCb: (config) => {
config.dev = { enableSelfContainedVaults: true };
return config;
},
},
() => {
let remote: string;
before(async () => {
const { vaults } = ExtensionProvider.getDWorkspace();
const cmd = new VaultConvertCommand();
sinon.stub(cmd, "gatherType").resolves("remote");
sinon.stub(cmd, "gatherVault").resolves(vaults[0]);
sinon.stub(cmd, "promptForFolderMove").resolves(true);
// Create a remote repository to be the upstream
remote = tmpDir().name;
await GitTestUtils.remoteCreate(remote);
sinon.stub(cmd, "gatherRemoteURL").resolves(remote);
await cmd.run();
});
after(async () => {
sinon.restore();
});
test("THEN updates .gitignore", async () => {
const { wsRoot } = ExtensionProvider.getDWorkspace();
const contents = await fs.readFile(path.join(wsRoot, ".gitignore"), {
encoding: "utf-8",
});
// Should have moved under dependencies
expect(
contents.match(
new RegExp(
`^dependencies${_.escapeRegExp(path.sep)}${path.basename(
remote
)}`,
"m"
)
)
).toBeTruthy();
});
test("THEN updates config", async () => {
const { wsRoot } = ExtensionProvider.getDWorkspace();
const config = DConfig.getRaw(wsRoot) as IntermediateDendronConfig;
expect(ConfigUtils.getVaults(config)[0].remote).toEqual({
type: "git",
url: remote,
});
});
test("THEN the vault is moved to the right folder", async () => {
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
const vault = vaults[0];
expect(
await fs.pathExists(
path.join(wsRoot, VaultUtils.getRelPath(vault), "root.md")
)
).toBeTruthy();
expect(vault.fsPath.startsWith(FOLDERS.DEPENDENCIES)).toBeTruthy();
expect(vault.fsPath.endsWith(path.basename(remote))).toBeTruthy();
});
test("THEN the folder is a git repository", async () => {
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
const git = new Git({ localUrl: path.join(wsRoot, vaults[0].fsPath) });
expect(await git.getRemote()).toEqual("origin");
expect(await git.getCurrentBranch()).toBeTruthy();
});
describe("AND converting that back to a local vault", () => {
before(async () => {
const { vaults } = ExtensionProvider.getDWorkspace();
const cmd = new VaultConvertCommand();
sinon.stub(cmd, "gatherType").resolves("local");
sinon.stub(cmd, "gatherVault").resolves(vaults[0]);
sinon.stub(cmd, "promptForFolderMove").resolves(true);
await cmd.run();
});
after(async () => {
sinon.restore();
});
test("THEN updates .gitignore", async () => {
const { wsRoot } = ExtensionProvider.getDWorkspace();
const contents = await fs.readFile(path.join(wsRoot, ".gitignore"), {
encoding: "utf-8",
});
expect(contents.match(/^dependencies/m)).toBeFalsy();
});
test("THEN updates config", async () => {
const { wsRoot } = ExtensionProvider.getDWorkspace();
const config = DConfig.getRaw(wsRoot) as IntermediateDendronConfig;
expect(ConfigUtils.getVaults(config)[0].remote).toBeFalsy();
});
test("THEN the vault is moved to the right folder", async () => {
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
const vault = vaults[0];
expect(
await fs.pathExists(
path.join(wsRoot, VaultUtils.getRelPath(vault), "root.md")
)
).toBeTruthy();
expect(
vault.fsPath.startsWith(
path.join(FOLDERS.DEPENDENCIES, FOLDERS.LOCAL_DEPENDENCY)
)
).toBeTruthy();
});
test("THEN the folder is NOT a git repository", async () => {
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
const git = new Git({
localUrl: path.join(wsRoot, vaults[0].fsPath),
});
expect(await git.getRemote()).toBeFalsy();
});
});
}
);
describeMultiWS(
"WHEN given a bad remote URL",
{ preSetupHook: ENGINE_HOOKS_MULTI.setupBasicMulti },
() => {
before(async () => {
const { vaults } = ExtensionProvider.getDWorkspace();
const cmd = new VaultConvertCommand();
sinon.stub(cmd, "gatherType").resolves("remote");
sinon.stub(cmd, "gatherVault").resolves(vaults[0]);
// Bad remote, not actually a vault
const remote = tmpDir().name;
sinon.stub(cmd, "gatherRemoteURL").resolves(remote);
await cmd.run();
});
after(async () => {
sinon.restore();
});
test("THEN conversion fails mid-operation", async () => {
// config is updated after the remote is fully set up, so if the config has been updated we know that we were able to set up and push to remote
const { wsRoot } = ExtensionProvider.getDWorkspace();
const config = DConfig.getRaw(wsRoot) as IntermediateDendronConfig;
expect(ConfigUtils.getVaults(config)[0].remote).toBeFalsy();
});
describe("AND running the conversion command again", () => {
before(async () => {
const { vaults } = ExtensionProvider.getDWorkspace();
const cmd = new VaultConvertCommand();
sinon.stub(cmd, "gatherType").resolves("remote");
sinon.stub(cmd, "gatherVault").resolves(vaults[0]);
// Create a remote repository to be the upstream
const remote = tmpDir().name;
await GitTestUtils.remoteCreate(remote);
sinon.stub(cmd, "gatherRemoteURL").resolves(remote);
await cmd.run();
});
after(async () => {
sinon.restore();
});
test("THEN the conversion completes", async () => {
// config is updated after the remote is fully set up, so if the config has been updated we know that we were able to set up and push to remote
const { wsRoot } = ExtensionProvider.getDWorkspace();
const config = DConfig.getRaw(wsRoot) as IntermediateDendronConfig;
expect(ConfigUtils.getVaults(config)[0].remote).toBeTruthy();
});
});
}
);
});
Example #11
Source File: LookupViewModel.test.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
describe(`GIVEN a LookupV3QuickPick`, () => {
const qp =
vscode.window.createQuickPick<DNodePropsQuickInputV2>() as DendronQuickPickerV2;
qp.buttons = [
VaultSelectButton.create({ pressed: false }),
MultiSelectBtn.create({ pressed: false }),
CopyNoteLinkBtn.create(false),
DirectChildFilterBtn.create(false),
SelectionExtractBtn.create(false),
Selection2LinkBtn.create(false),
Selection2ItemsBtn.create({
pressed: false,
}),
JournalBtn.create({
pressed: false,
}),
ScratchBtn.create({
pressed: false,
}),
TaskBtn.create(false),
HorizontalSplitBtn.create(false),
];
const viewModel: ILookupViewModel = {
selectionState: new TwoWayBinding<LookupSelectionTypeEnum>(
LookupSelectionTypeEnum.none
),
vaultSelectionMode: new TwoWayBinding<VaultSelectionMode>(
VaultSelectionMode.auto
),
isMultiSelectEnabled: new TwoWayBinding<boolean>(false),
isCopyNoteLinkEnabled: new TwoWayBinding<boolean>(false),
isApplyDirectChildFilter: new TwoWayBinding<boolean>(false),
nameModifierMode: new TwoWayBinding<LookupNoteTypeEnum>(
LookupNoteTypeEnum.none
),
isSplitHorizontally: new TwoWayBinding<boolean>(false),
};
let viewToTest: LookupV3QuickPickView | undefined;
before(() => {
viewToTest = new LookupV3QuickPickView(qp, viewModel);
});
after(() => {
if (viewToTest) {
viewToTest.dispose();
viewToTest = undefined;
}
});
describe(`WHEN mode changed to selection2Items`, () => {
it(`THEN selection2Items button checked and Extract and toLink buttons unchecked`, () => {
viewModel.selectionState.value = LookupSelectionTypeEnum.selection2Items;
expect(isButtonPressed("selection2Items", qp.buttons)).toBeTruthy();
expect(isButtonPressed("selectionExtract", qp.buttons)).toBeFalsy();
expect(isButtonPressed("selection2link", qp.buttons)).toBeFalsy();
});
});
describe(`WHEN mode changed to selection2Link`, () => {
it(`THEN selection2Link button checked and Extract and toItems buttons unchecked`, () => {
viewModel.selectionState.value = LookupSelectionTypeEnum.selection2link;
expect(isButtonPressed("selection2Items", qp.buttons)).toBeFalsy();
expect(isButtonPressed("selectionExtract", qp.buttons)).toBeFalsy();
expect(isButtonPressed("selection2link", qp.buttons)).toBeTruthy();
});
});
describe(`WHEN mode changed to selection2Extract`, () => {
it(`THEN selection2Extract button checked and toItems and toLink buttons unchecked`, () => {
viewModel.selectionState.value = LookupSelectionTypeEnum.selectionExtract;
expect(isButtonPressed("selection2Items", qp.buttons)).toBeFalsy();
expect(isButtonPressed("selectionExtract", qp.buttons)).toBeTruthy();
expect(isButtonPressed("selection2link", qp.buttons)).toBeFalsy();
});
});
describe(`WHEN mode changed to None`, () => {
it(`THEN extract, toItems, toLink buttons all unchecked`, () => {
viewModel.selectionState.value = LookupSelectionTypeEnum.none;
expect(isButtonPressed("selection2Items", qp.buttons)).toBeFalsy();
expect(isButtonPressed("selectionExtract", qp.buttons)).toBeFalsy();
expect(isButtonPressed("selection2link", qp.buttons)).toBeFalsy();
});
});
describe(`WHEN vaultSelection is alwaysPrompt`, () => {
it(`THEN vaultSelection button is checked`, () => {
viewModel.vaultSelectionMode.value = VaultSelectionMode.alwaysPrompt;
expect(isButtonPressed("selectVault", qp.buttons)).toBeTruthy();
});
});
describe(`WHEN vaultSelection is smart`, () => {
it(`THEN vaultSelection button is unchecked`, () => {
viewModel.vaultSelectionMode.value = VaultSelectionMode.smart;
expect(isButtonPressed("selectVault", qp.buttons)).toBeFalsy();
});
});
describe(`WHEN multiSelect is enabled`, () => {
it(`THEN multiSelect button is checked`, () => {
viewModel.isMultiSelectEnabled.value = true;
expect(isButtonPressed("multiSelect", qp.buttons)).toBeTruthy();
});
});
describe(`WHEN multiSelect is disabled`, () => {
it(`THEN multiSelect button is unchecked`, () => {
viewModel.isMultiSelectEnabled.value = false;
expect(isButtonPressed("multiSelect", qp.buttons)).toBeFalsy();
});
});
// Copy Note Link State
describe(`WHEN copyNoteLink is enabled`, () => {
it(`THEN copyNoteLink button is checked`, () => {
viewModel.isCopyNoteLinkEnabled.value = true;
expect(isButtonPressed("copyNoteLink", qp.buttons)).toBeTruthy();
});
});
describe(`WHEN copyNoteLink is disabled`, () => {
it(`THEN copyNoteLink button is unchecked`, () => {
viewModel.isCopyNoteLinkEnabled.value = false;
expect(isButtonPressed("copyNoteLink", qp.buttons)).toBeFalsy();
});
});
// Direct Child Only state
describe(`WHEN directChildOnly is enabled`, () => {
it(`THEN directChildOnly button is checked`, () => {
viewModel.isApplyDirectChildFilter.value = true;
expect(isButtonPressed("directChildOnly", qp.buttons)).toBeTruthy();
});
});
describe(`WHEN directChildOnly is disabled`, () => {
it(`THEN directChildOnly button is unchecked`, () => {
viewModel.isApplyDirectChildFilter.value = false;
expect(isButtonPressed("directChildOnly", qp.buttons)).toBeFalsy();
});
});
// Horizontal Split state
describe(`WHEN horizontal split is enabled`, () => {
it(`THEN horizontal button is checked`, () => {
viewModel.isSplitHorizontally.value = true;
expect(isButtonPressed("horizontal", qp.buttons)).toBeTruthy();
});
});
describe(`WHEN horizontal split is disabled`, () => {
it(`THEN horizontal button is unchecked`, () => {
viewModel.isSplitHorizontally.value = false;
expect(isButtonPressed("horizontal", qp.buttons)).toBeFalsy();
});
});
// Name Modifier Options (Journal / Scratch / Task):
describe(`WHEN name modifier mode changed to Journal`, () => {
it(`THEN journal button checked and scratch and task buttons unchecked`, () => {
viewModel.nameModifierMode.value = LookupNoteTypeEnum.journal;
expect(
isButtonPressed(LookupNoteTypeEnum.journal, qp.buttons)
).toBeTruthy();
expect(
isButtonPressed(LookupNoteTypeEnum.scratch, qp.buttons)
).toBeFalsy();
expect(isButtonPressed(LookupNoteTypeEnum.task, qp.buttons)).toBeFalsy();
});
});
describe(`WHEN name modifier mode changed to Scratch`, () => {
it(`THEN scratch button checked and journal and task buttons unchecked`, () => {
viewModel.nameModifierMode.value = LookupNoteTypeEnum.scratch;
expect(
isButtonPressed(LookupNoteTypeEnum.journal, qp.buttons)
).toBeFalsy();
expect(
isButtonPressed(LookupNoteTypeEnum.scratch, qp.buttons)
).toBeTruthy();
expect(isButtonPressed(LookupNoteTypeEnum.task, qp.buttons)).toBeFalsy();
});
});
describe(`WHEN name modifier mode changed to Task`, () => {
it(`THEN task button checked and journal and scratch buttons unchecked`, () => {
viewModel.nameModifierMode.value = LookupNoteTypeEnum.task;
expect(
isButtonPressed(LookupNoteTypeEnum.journal, qp.buttons)
).toBeFalsy();
expect(
isButtonPressed(LookupNoteTypeEnum.scratch, qp.buttons)
).toBeFalsy();
expect(isButtonPressed(LookupNoteTypeEnum.task, qp.buttons)).toBeTruthy();
});
});
describe(`WHEN name modifier mode changed to None`, () => {
it(`THEN journal, scratch, task buttons all unchecked`, () => {
viewModel.nameModifierMode.value = LookupNoteTypeEnum.none;
expect(
isButtonPressed(LookupNoteTypeEnum.journal, qp.buttons)
).toBeFalsy();
expect(
isButtonPressed(LookupNoteTypeEnum.scratch, qp.buttons)
).toBeFalsy();
expect(isButtonPressed(LookupNoteTypeEnum.task, qp.buttons)).toBeFalsy();
});
});
});
Example #12
Source File: BaseExportPodCommand.test.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
suite("BaseExportPodCommand", function () {
describe("GIVEN a BaseExportPodCommand implementation", () => {
describeSingleWS(
"WHEN exporting a note scope",
{
postSetupHook: ENGINE_HOOKS.setupBasic,
},
() => {
test("THEN note prop should be in the export payload", async () => {
const cmd = new TestExportPodCommand(
ExtensionProvider.getExtension()
);
const { wsRoot, vaults } = ExtensionProvider.getDWorkspace();
const notePath = path.join(
vault2Path({ vault: vaults[0], wsRoot }),
"root.md"
);
await VSCodeUtils.openFileInEditor(vscode.Uri.file(notePath));
const payload = await cmd.enrichInputs({
exportScope: PodExportScope.Note,
});
expect((payload?.payload as NoteProps[])[0].fname).toEqual("root");
expect((payload?.payload as NoteProps[]).length).toEqual(1);
});
test("AND note is dirty, THEN a onDidSaveTextDocument should be fired", (done) => {
const cmd = new TestExportPodCommand(
ExtensionProvider.getExtension()
);
const engine = ExtensionProvider.getEngine();
const testNote = engine.notes["foo"];
const textToAppend = "BaseExportPodCommand testing";
// onEngineNoteStateChanged is not being triggered by save so test to make sure that save is being triggered instead
const disposable = vscode.workspace.onDidSaveTextDocument(
(textDocument) => {
testAssertsInsideCallback(() => {
expect(
textDocument.getText().includes(textToAppend)
).toBeTruthy();
expect(textDocument.fileName.endsWith("foo.md")).toBeTruthy();
disposable.dispose();
cmd.dispose();
}, done);
}
);
ExtensionProvider.getWSUtils()
.openNote(testNote)
.then(async (editor) => {
editor
.edit(async (editBuilder) => {
const line = editor.document.getText().split("\n").length;
editBuilder.insert(
new vscode.Position(line, 0),
textToAppend
);
})
.then(async () => {
cmd.run();
});
});
});
test("AND note is clean, THEN a onDidSaveTextDocument should not be fired", (done) => {
const cmd = new TestExportPodCommand(
ExtensionProvider.getExtension()
);
const engine = ExtensionProvider.getEngine();
const testNote = engine.notes["foo"];
vscode.workspace.onDidSaveTextDocument(() => {
assert(false, "Callback not expected");
});
ExtensionProvider.getWSUtils()
.openNote(testNote)
.then(async () => {
cmd.run();
});
// Small sleep to ensure callback doesn't fire.
waitInMilliseconds(10).then(() => done());
});
}
);
describeMultiWS(
"WHEN exporting a hierarchy scope",
{
preSetupHook: async ({ wsRoot, vaults }) => {
await ENGINE_HOOKS_MULTI.setupBasicMulti({ wsRoot, vaults });
await NoteTestUtilsV4.createNote({
wsRoot,
vault: vaults[1],
fname: "foo.test",
});
},
},
() => {
test("THEN hierarchy note props should be in the export payload AND a note with a hierarchy match but in a different vault should not appear", async () => {
const cmd = new TestExportPodCommand(
ExtensionProvider.getExtension()
);
const payload = await cmd.enrichInputs({
exportScope: PodExportScope.Hierarchy,
});
// 'foo' note and its child: foo.test should not appear
expect(payload?.payload.length).toEqual(2);
});
after(() => {
sinon.restore();
});
}
);
describeMultiWS(
"WHEN exporting a workspace scope",
{
preSetupHook: ENGINE_HOOKS.setupBasic,
},
() => {
test("THEN workspace note props should be in the export payload", async () => {
const cmd = new TestExportPodCommand(
ExtensionProvider.getExtension()
);
const payload = await cmd.enrichInputs({
exportScope: PodExportScope.Workspace,
});
expect(payload?.payload.length).toEqual(6);
});
}
);
describeMultiWS(
"WHEN exporting a lookup based scope",
{
preSetupHook: async ({ wsRoot, vaults }) => {
await ENGINE_HOOKS.setupBasic({ wsRoot, vaults });
await NoteTestUtilsV4.createNote({
wsRoot,
vault: vaults[0],
fname: "test-note-for-pod1",
});
await NoteTestUtilsV4.createNote({
wsRoot,
vault: vaults[0],
fname: "test-note-for-pod2",
});
},
},
() => {
let sandbox: sinon.SinonSandbox;
beforeEach(() => {
sandbox = sinon.createSandbox();
});
afterEach(() => {
sandbox.restore();
});
test("THEN lookup is prompted and lookup result should be the export payload", async () => {
const cmd = new TestExportPodCommand(
ExtensionProvider.getExtension()
);
const engine = ExtensionProvider.getEngine();
const { wsRoot, vaults } = engine;
const testNote1 = NoteUtils.getNoteByFnameV5({
fname: "test-note-for-pod1",
notes: engine.notes,
wsRoot,
vault: vaults[0],
}) as NoteProps;
const testNote2 = NoteUtils.getNoteByFnameV5({
fname: "test-note-for-pod2",
notes: engine.notes,
wsRoot,
vault: vaults[0],
}) as NoteProps;
const selectedItems = [
{ ...testNote1, label: "" },
{ ...testNote2, label: "" },
];
const lookupStub = sandbox
.stub(PodUIControls, "promptForScopeLookup")
.resolves({
selectedItems,
onAcceptHookResp: [],
});
await cmd.enrichInputs({
exportScope: PodExportScope.Lookup,
});
expect(lookupStub.calledOnce).toBeTruthy();
await cmd.enrichInputs({
exportScope: PodExportScope.LinksInSelection,
});
expect(lookupStub.calledTwice).toBeTruthy();
});
}
);
describeMultiWS(
"WHEN exporting a vault scope",
{
preSetupHook: ENGINE_HOOKS.setupBasic,
},
() => {
test("THEN quickpick is prompted and selected vault's notes shoul be export payload", async () => {
const cmd = new TestExportPodCommand(
ExtensionProvider.getExtension()
);
const engine = ExtensionProvider.getEngine();
const { vaults } = engine;
stubQuickPick(vaults[0]);
const payload = await cmd.enrichInputs({
exportScope: PodExportScope.Vault,
});
expect(payload?.payload.length).toEqual(4);
});
}
);
});
});
Example #13
Source File: testUtilsV3.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
/**
* Use to run tests with a multi-vault workspace. Used in the same way as
* regular `describe`. For example:
* ```ts
* describeMultiWS(
* "WHEN workspace type is not specified",
* {
* preSetupHook: ENGINE_HOOKS.setupBasic,
* },
* () => {
* test("THEN initializes correctly", (done) => {
* const { engine, _wsRoot, _vaults } = getDWorkspace();
* const testNote = engine.notes["foo"];
* expect(testNote).toBeTruthy();
* done();
* });
* }
* );
* ```
* @param title
* @param opts
* @param fn - the test() functions to execute. NOTE: This function CANNOT be
* async, or else the test may not fail reliably when your expect or assert
* conditions are not met. ^eq30h1lt0zat
*/
export function describeMultiWS(
title: string,
opts: SetupLegacyWorkspaceMultiOpts & {
/**
* Run after we stub vscode mock workspace, but before the workspace is created
*/
beforeHook?: (opts: { ctx: ExtensionContext }) => Promise<void>;
/**
* Run after the workspace is crated, but before dendron is activated
*/
preActivateHook?: (opts: {
ctx: ExtensionContext;
wsRoot: string;
vaults: DVault[];
}) => Promise<void>;
/**
* @deprecated Please use an `after()` hook instead
*/
afterHook?: (opts: { ctx: ExtensionContext }) => Promise<void>;
/**
* Custom timeout for test in milleseconds
* You will need to set this when stepping through mocha tests using breakpoints
* otherwise the test will timeout during debugging
* See [[Breakpoints|dendron://dendron.docs/pkg.plugin-core.qa.debug#breakpoints]] for more details
*/
timeout?: number;
noSetInstallStatus?: boolean;
},
fn: (ctx: ExtensionContext) => void
) {
describe(title, function () {
if (opts.timeout) {
this.timeout(opts.timeout);
}
const ctx = opts.ctx ?? VSCodeUtils.getOrCreateMockContext();
before(async () => {
setupWorkspaceStubs({ ...opts, ctx });
if (opts.beforeHook) {
await opts.beforeHook({ ctx });
}
const out = await setupLegacyWorkspaceMulti({ ...opts, ctx });
if (opts.preActivateHook) {
await opts.preActivateHook({ ctx, ...out });
}
await _activate(ctx);
});
const result = fn(ctx);
assertTestFnNotAsync(result);
// Release all registered resouces such as commands and providers
after(async () => {
if (opts.afterHook) {
await opts.afterHook({ ctx });
}
cleanupWorkspaceStubs(ctx);
});
});
}