How to use addCleanup method in testing-library-react-hooks

Best JavaScript code snippet using testing-library-react-hooks

vscode-tests.js

Source:vscode-tests.js Github

copy

Full Screen

...395 ]);396 },397 "deactivating plugin removes diagnostics": async ({ addCleanup }) => {398 let deactivated = false;399 addCleanup(async () => {400 if (!deactivated) {401 await qljsExtension.deactivate();402 }403 });404 await qljsExtension.activate();405 let scratchDirectory = makeScratchDirectory({ addCleanup });406 let helloFilePath = path.join(scratchDirectory, "hello.js");407 fs.writeFileSync(helloFilePath, "let x = 3;\nlet x = 4;\n");408 let helloURI = vscode.Uri.file(helloFilePath);409 let helloDocument = await vscode.workspace.openTextDocument(helloURI);410 let helloEditor = await vscode.window.showTextDocument(helloDocument);411 await waitUntilAnyDiagnosticsAsync(helloURI);412 await qljsExtension.deactivate();413 deactivated = true;414 await waitUntilNoDiagnosticsAsync(helloURI);415 },416 "opened .js file uses quick-lint-js.config from disk": async ({417 addCleanup,418 }) => {419 let messageMocker = VSCodeMessageMocker.mock({ addCleanup });420 let scratchDirectory = makeScratchDirectory({ addCleanup });421 let jsFilePath = path.join(scratchDirectory, "hello.js");422 fs.writeFileSync(jsFilePath, "testGlobalVariable;\ndocument;");423 let jsURI = vscode.Uri.file(jsFilePath);424 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");425 fs.writeFileSync(426 configFilePath,427 '{"globals": {"testGlobalVariable": true}, "global-groups": ["ecmascript"]}'428 );429 await loadExtensionAsync({ addCleanup });430 let jsDocument = await vscode.workspace.openTextDocument(jsURI);431 let jsEditor = await vscode.window.showTextDocument(jsDocument);432 await waitUntilAnyDiagnosticsAsync(jsURI);433 let jsDiags = normalizeDiagnostics(jsURI);434 assert.deepStrictEqual(435 jsDiags.map(({ code, startLine }) => ({ code, startLine })),436 [437 {438 code: {439 target: "https://quick-lint-js.com/errors/E0057/",440 value: "E0057",441 },442 startLine: 1, // document443 },444 ]445 );446 messageMocker.assertNoMessages();447 },448 "I/O error loading quick-lint-js.config shows pop-up": async ({449 addCleanup,450 }) => {451 let messageMocker = VSCodeMessageMocker.mock({ addCleanup });452 let scratchDirectory = makeScratchDirectory({ addCleanup });453 let jsFilePath = path.join(scratchDirectory, "hello.js");454 fs.writeFileSync(jsFilePath, "variableDoesNotExist;");455 let jsURI = vscode.Uri.file(jsFilePath);456 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");457 fs.mkdirSync(configFilePath);458 await loadExtensionAsync({ addCleanup });459 let jsDocument = await vscode.workspace.openTextDocument(jsURI);460 let jsEditor = await vscode.window.showTextDocument(jsDocument);461 await waitUntilAnyDiagnosticsAsync(jsURI);462 messageMocker.assertAnyErrorMessageMatches(463 /Failed to load configuration file for .*hello\.js\. Using default configuration\.\nError details: failed to read from .*quick-lint-js\.config: .*/464 );465 },466 "opening .js file with error in quick-lint-js.config shows pop-up": async ({467 addCleanup,468 }) => {469 let messageMocker = VSCodeMessageMocker.mock({ addCleanup });470 let scratchDirectory = makeScratchDirectory({ addCleanup });471 let jsFilePath = path.join(scratchDirectory, "hello.js");472 fs.writeFileSync(jsFilePath, "variableDoesNotExist;");473 let jsURI = vscode.Uri.file(jsFilePath);474 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");475 fs.writeFileSync(configFilePath, "{SYNTAX ERROR}");476 await loadExtensionAsync({ addCleanup });477 let jsDocument = await vscode.workspace.openTextDocument(jsURI);478 let jsEditor = await vscode.window.showTextDocument(jsDocument);479 await waitUntilAnyDiagnosticsAsync(jsURI);480 messageMocker.assertAnyErrorMessageMatches(481 /Problems found in the config file for .*hello\.js \(.*quick-lint-js\.config\)./482 );483 },484 "clicking Open-Config button in quick-lint-js.config error pop-up opens config file":485 async ({ addCleanup }) => {486 let messageMocker = VSCodeMessageMocker.mock({ addCleanup });487 let scratchDirectory = makeScratchDirectory({ addCleanup });488 let jsFilePath = path.join(scratchDirectory, "hello.js");489 fs.writeFileSync(jsFilePath, "variableDoesNotExist;");490 let jsURI = vscode.Uri.file(jsFilePath);491 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");492 fs.writeFileSync(configFilePath, "{SYNTAX ERROR}");493 await loadExtensionAsync({ addCleanup });494 let jsDocument = await vscode.workspace.openTextDocument(jsURI);495 let jsEditor = await vscode.window.showTextDocument(jsDocument);496 await messageMocker.waitUntilAnyMessageAsync();497 assert.strictEqual(498 path.basename(vscode.window.activeTextEditor.document.fileName),499 "hello.js"500 );501 messageMocker.getErrorMessages()[0].clickButton("Open config");502 await pollAsync(async () => {503 assert.strictEqual(504 path.basename(vscode.window.activeTextEditor.document.fileName),505 "quick-lint-js.config"506 );507 });508 },509 "dismissing quick-lint-js.config error pop-up does not open config file":510 async ({ addCleanup }) => {511 let messageMocker = VSCodeMessageMocker.mock({ addCleanup });512 let scratchDirectory = makeScratchDirectory({ addCleanup });513 let jsFilePath = path.join(scratchDirectory, "hello.js");514 fs.writeFileSync(jsFilePath, "variableDoesNotExist;");515 let jsURI = vscode.Uri.file(jsFilePath);516 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");517 fs.writeFileSync(configFilePath, "{SYNTAX ERROR}");518 await loadExtensionAsync({ addCleanup });519 let jsDocument = await vscode.workspace.openTextDocument(jsURI);520 let jsEditor = await vscode.window.showTextDocument(jsDocument);521 await messageMocker.waitUntilAnyMessageAsync();522 messageMocker.getErrorMessages()[0].dismiss();523 // Wait for possible opening of quick-lint-js.config to take effect.524 await sleepAsync(100);525 assert.strictEqual(526 path.basename(vscode.window.activeTextEditor.document.fileName),527 "hello.js"528 );529 },530 "opened .js file uses opened quick-lint-js.config (not from disk)": async ({531 addCleanup,532 }) => {533 let scratchDirectory = makeScratchDirectory({ addCleanup });534 let jsFilePath = path.join(scratchDirectory, "hello.js");535 fs.writeFileSync(536 jsFilePath,537 "testGlobalVariableFromEditor;\ntestGlobalVariableFromDisk;"538 );539 let jsURI = vscode.Uri.file(jsFilePath);540 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");541 fs.writeFileSync(542 configFilePath,543 '{"globals": {"testGlobalVariableFromDisk": true}}'544 );545 let configURI = vscode.Uri.file(configFilePath);546 await loadExtensionAsync({ addCleanup });547 let configDocument = await vscode.workspace.openTextDocument(configURI);548 let configEditor = await vscode.window.showTextDocument(configDocument);549 await configEditor.edit((editBuilder) => {550 editBuilder.replace(551 new vscode.Range(new vscode.Position(0, 0), new vscode.Position(1, 0)),552 '{"globals": {"testGlobalVariableFromEditor": true}, "global-groups": ["ecmascript"]}'553 );554 });555 let jsDocument = await vscode.workspace.openTextDocument(jsURI);556 let jsEditor = await vscode.window.showTextDocument(jsDocument);557 await waitUntilAnyDiagnosticsAsync(jsURI);558 let jsDiags = normalizeDiagnostics(jsURI);559 assert.deepStrictEqual(560 jsDiags.map(({ code, startLine }) => ({ code, startLine })),561 [562 {563 code: {564 target: "https://quick-lint-js.com/errors/E0057/",565 value: "E0057",566 },567 startLine: 1, // testGlobalVariableFromDisk568 },569 ]570 );571 },572 "valid quick-lint-js.config has no diagnostics; should not be linted as a .js file":573 async ({ addCleanup }) => {574 let scratchDirectory = makeScratchDirectory({ addCleanup });575 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");576 fs.writeFileSync(577 configFilePath,578 '{"globals": {"testGlobalVariable": true}}'579 );580 let configURI = vscode.Uri.file(configFilePath);581 await loadExtensionAsync({ addCleanup });582 let configDocument = await vscode.workspace.openTextDocument(configURI);583 let configEditor = await vscode.window.showTextDocument(configDocument);584 // Wait for possible linting to take effect.585 await sleepAsync(100);586 let configDiags = normalizeDiagnostics(configURI);587 assert.deepStrictEqual(configDiags, []);588 },589 "opening invalid quick-lint-js.config shows diagnostics": async ({590 addCleanup,591 }) => {592 let scratchDirectory = makeScratchDirectory({ addCleanup });593 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");594 fs.writeFileSync(595 configFilePath,596 '{"globals": {"testGlobalVariable": "INVALID"}}'597 );598 let configURI = vscode.Uri.file(configFilePath);599 await loadExtensionAsync({ addCleanup });600 let configDocument = await vscode.workspace.openTextDocument(configURI);601 let configEditor = await vscode.window.showTextDocument(configDocument);602 await waitUntilAnyDiagnosticsAsync(configURI);603 let configDiags = normalizeDiagnostics(configURI);604 assert.deepStrictEqual(605 configDiags.map(({ code }) => code),606 [607 {608 target: "https://quick-lint-js.com/errors/E0171/",609 value: "E0171",610 },611 ]612 );613 },614 "making quick-lint-js.config invalid shows diagnostics": async ({615 addCleanup,616 }) => {617 let scratchDirectory = makeScratchDirectory({ addCleanup });618 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");619 fs.writeFileSync(620 configFilePath,621 '{"globals": {"testGlobalVariable": true}}'622 );623 let configURI = vscode.Uri.file(configFilePath);624 await loadExtensionAsync({ addCleanup });625 let configDocument = await vscode.workspace.openTextDocument(configURI);626 let configEditor = await vscode.window.showTextDocument(configDocument);627 await configEditor.edit((editBuilder) => {628 editBuilder.replace(629 new vscode.Range(630 new vscode.Position(0, '{"globals": {"testGlobalVariable": '.length),631 new vscode.Position(632 0,633 '{"globals": {"testGlobalVariable": true'.length634 )635 ),636 '"INVALID"'637 );638 });639 await waitUntilAnyDiagnosticsAsync(configURI);640 let configDiags = normalizeDiagnostics(configURI);641 assert.deepStrictEqual(642 configDiags.map(({ code }) => code),643 [644 {645 target: "https://quick-lint-js.com/errors/E0171/",646 value: "E0171",647 },648 ]649 );650 },651 "opened .js file uses quick-lint-js.config from disk after config editor is closed":652 async ({ addCleanup }) => {653 // TODO(strager): Enable this test when VS Code is fixed (or when we find a654 // workaround). In tests, VS Code does not send us didCloseTextDocument655 // notifications, so this test can't know when quick-lint-js.config is656 // closed.657 // https://github.com/microsoft/vscode/issues/130957658 return;659 let scratchDirectory = makeScratchDirectory({ addCleanup });660 let jsFilePath = path.join(scratchDirectory, "hello.js");661 fs.writeFileSync(662 jsFilePath,663 "testGlobalVariableFromEditor;\ntestGlobalVariableFromDiskModified;"664 );665 let jsURI = vscode.Uri.file(jsFilePath);666 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");667 fs.writeFileSync(668 configFilePath,669 '{"globals": {"testGlobalVariableFromDiskOriginal": true}}'670 );671 let configURI = vscode.Uri.file(configFilePath);672 await loadExtensionAsync({ addCleanup });673 let configDocument = await vscode.workspace.openTextDocument(configURI);674 let configEditor = await vscode.window.showTextDocument(configDocument);675 await configEditor.edit((editBuilder) => {676 editBuilder.replace(677 new vscode.Range(678 new vscode.Position(0, 0),679 new vscode.Position(1, 0)680 ),681 '{"globals": {"testGlobalVariableFromEditor": true}, "global-groups": ["ecmascript"]}'682 );683 });684 await vscode.commands.executeCommand(685 "workbench.action.closeActiveEditor"686 );687 fs.writeFileSync(688 configFilePath,689 '{"globals": {"testGlobalVariableFromDiskModified": true}}'690 );691 let jsDocument = await vscode.workspace.openTextDocument(jsURI);692 let jsEditor = await vscode.window.showTextDocument(jsDocument);693 await waitUntilAnyDiagnosticsAsync(jsURI);694 let jsDiags = normalizeDiagnostics(jsURI);695 assert.deepStrictEqual(696 jsDiags.map(({ code, startLine }) => ({ code, startLine })),697 [698 {699 code: {700 target: "https://quick-lint-js.com/errors/E0057/",701 value: "E0057",702 },703 startLine: 0, // testGlobalVariableFromEditor704 },705 ]706 );707 },708 "opened .js re-lints when changing open quick-lint-js.config": async ({709 addCleanup,710 }) => {711 let scratchDirectory = makeScratchDirectory({ addCleanup });712 let jsFilePath = path.join(scratchDirectory, "hello.js");713 fs.writeFileSync(jsFilePath, "testGlobalVariableFromEditor;");714 let jsURI = vscode.Uri.file(jsFilePath);715 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");716 fs.writeFileSync(configFilePath, "{}");717 let configURI = vscode.Uri.file(configFilePath);718 await loadExtensionAsync({ addCleanup });719 let jsDocument = await vscode.workspace.openTextDocument(jsURI);720 let jsEditor = await vscode.window.showTextDocument(721 jsDocument,722 vscode.ViewColumn.One723 );724 await waitUntilAnyDiagnosticsAsync(jsURI);725 let configDocument = await vscode.workspace.openTextDocument(configURI);726 let configEditor = await vscode.window.showTextDocument(727 configDocument,728 vscode.ViewColumn.Two729 );730 await configEditor.edit((editBuilder) => {731 editBuilder.replace(732 new vscode.Range(new vscode.Position(0, 0), new vscode.Position(1, 0)),733 '{"globals": {"testGlobalVariableFromEditor": true}}'734 );735 });736 await waitUntilNoDiagnosticsAsync(jsURI);737 },738 "opened .js re-lints when changing unopened quick-lint-js.config on disk":739 async ({ addCleanup }) => {740 let scratchDirectory = makeScratchDirectory({ addCleanup });741 let jsFilePath = path.join(scratchDirectory, "hello.js");742 fs.writeFileSync(jsFilePath, "testGlobalVariableFromDisk;");743 let jsURI = vscode.Uri.file(jsFilePath);744 let configFilePath = path.join(scratchDirectory, "quick-lint-js.config");745 fs.writeFileSync(configFilePath, "{}");746 let configURI = vscode.Uri.file(configFilePath);747 await loadExtensionAsync({ addCleanup });748 let jsDocument = await vscode.workspace.openTextDocument(jsURI);749 let jsEditor = await vscode.window.showTextDocument(750 jsDocument,751 vscode.ViewColumn.One752 );753 await waitUntilAnyDiagnosticsAsync(jsURI);754 fs.writeFileSync(755 configFilePath,756 '{"globals": {"testGlobalVariableFromDisk": true}}'757 );758 await waitUntilNoDiagnosticsAsync(jsURI);759 },760 "no output channel by default": async ({ addCleanup }) => {761 let outputChannelMocker = VSCodeOutputChannelMocker.mock({ addCleanup });762 await loadExtensionAsync({ addCleanup });763 await causeLogMessagesAsync({ addCleanup });764 assert.deepStrictEqual(outputChannelMocker.getOutputChannels(), []);765 },766 "output channel gets messages if logging is enabled": async ({767 addCleanup,768 }) => {769 let outputChannelMocker = VSCodeOutputChannelMocker.mock({ addCleanup });770 await vscode.workspace771 .getConfiguration("quick-lint-js")772 .update("logging", "verbose", vscode.ConfigurationTarget.Workspace);773 addCleanup(resetConfigurationAsync);774 await loadExtensionAsync({ addCleanup });775 await causeLogMessagesAsync({ addCleanup });776 assert.deepStrictEqual(777 outputChannelMocker.getOutputChannels().map((c) => c.name),778 ["quick-lint-js"]779 );780 let channel = outputChannelMocker.getOutputChannels()[0];781 assert.ok(782 channel._data.length > 0,783 "at least one message should have been logged by opening the file"784 );785 },786 "output channel gets messages if logging is enabled after loading extension":787 async ({ addCleanup }) => {788 let outputChannelMocker = VSCodeOutputChannelMocker.mock({ addCleanup });789 await loadExtensionAsync({ addCleanup });790 await causeLogMessagesAsync({ addCleanup });791 await vscode.workspace792 .getConfiguration("quick-lint-js")793 .update("logging", "verbose", vscode.ConfigurationTarget.Workspace);794 addCleanup(resetConfigurationAsync);795 await pollAsync(async () => {796 assert.deepStrictEqual(797 outputChannelMocker.getOutputChannels().map((c) => c.name),798 ["quick-lint-js"]799 );800 let channel = outputChannelMocker.getOutputChannels()[0];801 assert.ok(802 channel._data.length > 0,803 "at least one message should have been logged by enabling logging"804 );805 });806 },807 "output channel gets no more messages if logging is disabled after loading extension":808 async ({ addCleanup }) => {809 let outputChannelMocker = VSCodeOutputChannelMocker.mock({ addCleanup });810 await vscode.workspace811 .getConfiguration("quick-lint-js")812 .update("logging", "verbose", vscode.ConfigurationTarget.Workspace);813 addCleanup(resetConfigurationAsync);814 await loadExtensionAsync({ addCleanup });815 await causeLogMessagesAsync({ addCleanup });816 await vscode.workspace817 .getConfiguration("quick-lint-js")818 .update("logging", "off", vscode.ConfigurationTarget.Workspace);819 await waitForAsynchronousLogMessagesAsync();820 let messagesAfterDisablingLogging =821 outputChannelMocker.getOutputChannels()[0]._data;822 await causeLogMessagesAsync({ addCleanup });823 let messages = outputChannelMocker.getOutputChannels()[0]._data;824 assert.strictEqual(messages, messagesAfterDisablingLogging);825 },826 "enabling then disabling then enabling logging reuses output channel":827 async ({ addCleanup }) => {828 let outputChannelMocker = VSCodeOutputChannelMocker.mock({ addCleanup });829 await vscode.workspace830 .getConfiguration("quick-lint-js")831 .update("logging", "verbose", vscode.ConfigurationTarget.Workspace);832 addCleanup(resetConfigurationAsync);833 await loadExtensionAsync({ addCleanup });834 await causeLogMessagesAsync({ addCleanup });835 await vscode.workspace836 .getConfiguration("quick-lint-js")837 .update("logging", "off", vscode.ConfigurationTarget.Workspace);838 let messagesAfterDisablingLogging =839 outputChannelMocker.getOutputChannels()[0]._data;840 await vscode.workspace841 .getConfiguration("quick-lint-js")842 .update("logging", "verbose", vscode.ConfigurationTarget.Workspace);843 await causeLogMessagesAsync({ addCleanup });844 assert.deepStrictEqual(845 outputChannelMocker.getOutputChannels().map((c) => c.name),846 ["quick-lint-js"]847 );848 let messagesAfterReenablingLogging =849 outputChannelMocker.getOutputChannels()[0]._data;850 assert.ok(851 messagesAfterReenablingLogging.startsWith(messagesAfterDisablingLogging)852 );853 },854 // TODO(strager): Allow the user to delete the extenion, thereby deleting855 // the output channel.856};857if (os.platform() === "linux") {858 tests = {859 ...tests,860 "Linux: inotify watch error shows pop-up": async ({ addCleanup }) => {861 let messageMocker = VSCodeMessageMocker.mock({ addCleanup });862 mockInotifyErrors({863 addCleanup,864 addWatchError: os.constants.errno.ENOSPC,865 });866 let scratchDirectory = makeScratchDirectory({ addCleanup });867 let jsFilePath = path.join(scratchDirectory, "hello.js");868 fs.writeFileSync(jsFilePath, "");869 let jsURI = vscode.Uri.file(jsFilePath);870 await loadExtensionAsync({ addCleanup });871 let jsDocument = await vscode.workspace.openTextDocument(jsURI);872 let jsEditor = await vscode.window.showTextDocument(jsDocument);873 await messageMocker.waitUntilAnyMessageAsync();874 messageMocker.assertAnyWarningMessageMatches(875 /failed to watch .* for changes/i876 );877 },878 "Linux: inotify init error shows pop-up": async ({ addCleanup }) => {879 let messageMocker = VSCodeMessageMocker.mock({ addCleanup });880 mockInotifyErrors({ addCleanup, initError: os.constants.errno.EMFILE });881 let scratchDirectory = makeScratchDirectory({ addCleanup });882 let jsFilePath = path.join(scratchDirectory, "hello.js");883 fs.writeFileSync(jsFilePath, "");884 let jsURI = vscode.Uri.file(jsFilePath);885 await loadExtensionAsync({ addCleanup });886 let jsDocument = await vscode.workspace.openTextDocument(jsURI);887 let jsEditor = await vscode.window.showTextDocument(jsDocument);888 await messageMocker.waitUntilAnyMessageAsync();889 // TODO(strager): Improve the message.890 messageMocker.assertAnyWarningMessageMatches(891 /failed to watch for changes/i892 );893 },894 };895}896if (os.platform() === "darwin") {897 tests = {898 ...tests,899 "BSD: directory watch error shows pop-up": async ({ addCleanup }) => {900 let messageMocker = VSCodeMessageMocker.mock({ addCleanup });901 mockKqueueErrors({902 addCleanup,903 directoryOpenError: os.constants.errno.EMFILE,904 });905 let scratchDirectory = makeScratchDirectory({ addCleanup });906 let jsFilePath = path.join(scratchDirectory, "hello.js");907 fs.writeFileSync(jsFilePath, "");908 let jsURI = vscode.Uri.file(jsFilePath);909 await loadExtensionAsync({ addCleanup });910 let jsDocument = await vscode.workspace.openTextDocument(jsURI);911 let jsEditor = await vscode.window.showTextDocument(jsDocument);912 await messageMocker.waitUntilAnyMessageAsync();913 messageMocker.assertAnyWarningMessageMatches(914 /failed to watch .* for changes/i915 );916 },917 };918}919if (["darwin", "linux"].includes(os.platform())) {920 tests = {921 ...tests,922 "watch error only shows pop-up once": async ({ addCleanup }) => {923 let messageMocker = VSCodeMessageMocker.mock({ addCleanup });924 switch (os.platform()) {925 case "darwin":926 mockKqueueErrors({927 addCleanup,928 directoryOpenError: os.constants.errno.EMFILE,929 });930 break;931 case "linux":932 mockInotifyErrors({933 addCleanup,934 addWatchError: os.constants.errno.ENOSPC,935 });936 break;937 }938 let scratchDirectory = makeScratchDirectory({ addCleanup });939 let jsFilePath = path.join(scratchDirectory, "hello.js");940 fs.writeFileSync(jsFilePath, "");941 let jsURI = vscode.Uri.file(jsFilePath);942 await loadExtensionAsync({ addCleanup });943 let jsDocument = await vscode.workspace.openTextDocument(jsURI);944 await vscode.window.showTextDocument(jsDocument);945 await messageMocker.waitUntilAnyMessageAsync();946 assert.strictEqual(947 messageMocker.getWarningMessages().length,948 1,949 `Expected exactly one warning message. Got messages: ${messageMocker.getMessagesDebugString()}`950 );951 messageMocker.clearRememberedMessages();952 fs.mkdirSync(path.join(scratchDirectory, "dir"));953 let otherJSFilePath = path.join(scratchDirectory, "other.js");954 fs.writeFileSync(otherJSFilePath, "SYNTAX ERROR");955 let otherJSURI = vscode.Uri.file(otherJSFilePath);956 let otherJSDocument = await vscode.workspace.openTextDocument(otherJSURI);957 await vscode.window.showTextDocument(otherJSDocument);958 await waitUntilAnyDiagnosticsAsync(otherJSURI);959 assert.deepStrictEqual(960 messageMocker.getWarningMessages(),961 [],962 `Expected no more warning messages. Got messages: ${messageMocker.getMessagesDebugString()}`963 );964 },965 };966}967for (let testName in tests) {968 let realTestFunction = tests[testName];969 tests[testName] = (fixture) => {970 fixture.addCleanup(async () => {971 await cleanUpVSCodeEditorsAsync();972 });973 return realTestFunction(fixture);974 };975}976async function cleanUpVSCodeEditorsAsync() {977 await vscode.commands.executeCommand("workbench.action.closeAllEditors");978}979async function waitUntilAnyDiagnosticsAsync(documentURI) {980 await pollAsync(async () => {981 let diags = normalizeDiagnostics(documentURI);982 assert.strictEqual(diags.length >= 1, true);983 });984}985async function waitUntilNoDiagnosticsAsync(documentURI) {986 await pollAsync(async () => {987 let diags = normalizeDiagnostics(documentURI);988 assert.deepStrictEqual(diags, []);989 });990}991class VSCodeMessageMocker {992 static mock({ addCleanup }) {993 let mocker = new VSCodeMessageMocker();994 let methodsToMock = [995 "showErrorMessage",996 "showInformationMessage",997 "showWarningMessage",998 ];999 for (let methodToMock of methodsToMock) {1000 mocker._mockMethod(methodToMock, { addCleanup });1001 }1002 return mocker;1003 }1004 constructor() {1005 this._messages = [];1006 }1007 getMessagesDebugString() {1008 return JSON.stringify(this._messages);1009 }1010 getErrorMessages() {1011 return this._messages.filter((m) => m.method === "showErrorMessage");1012 }1013 getWarningMessages() {1014 return this._messages.filter((m) => m.method === "showWarningMessage");1015 }1016 clearRememberedMessages() {1017 this._messages.length = 0;1018 }1019 assertNoMessages() {1020 assert.deepStrictEqual(this._messages, []);1021 }1022 assertAnyErrorMessageMatches(regExp) {1023 assert.strictEqual(1024 this.getErrorMessages().some((m) => regExp.test(m.message)),1025 true,1026 `Expected message indicating IO error. Got messages: ${this.getMessagesDebugString()}`1027 );1028 }1029 assertAnyWarningMessageMatches(regExp) {1030 assert.strictEqual(1031 this.getWarningMessages().some((m) => regExp.test(m.message)),1032 true,1033 `Expected warning message. Got messages: ${this.getMessagesDebugString()}`1034 );1035 }1036 async waitUntilAnyMessageAsync() {1037 await pollAsync(async () => {1038 assert.ok(this._messages.length >= 1);1039 });1040 }1041 _mockMethod(methodToMock, { addCleanup }) {1042 let originalMethod = vscode.window[methodToMock];1043 addCleanup(() => {1044 vscode.window[methodToMock] = originalMethod;1045 });1046 let self = this;1047 vscode.window[methodToMock] = function showMessageMock(message, ...args) {1048 console.log(1049 `called: vscode.window.${methodToMock}(${JSON.stringify(message)}, ...)`1050 );1051 let buttons = args;1052 return new Promise((resolve, _reject) => {1053 self._messages.push({1054 message: message,1055 method: methodToMock,1056 clickButton(buttonLabel) {1057 assert.ok(1058 buttons.includes(buttonLabel),1059 `Cannot click button ${JSON.stringify(1060 buttonLabel1061 )}; available buttons are: ${JSON.stringify(buttons)}`1062 );1063 resolve(buttonLabel);1064 },1065 dismiss() {1066 resolve(undefined);1067 },1068 });1069 });1070 };1071 }1072}1073class VSCodeOutputChannelMocker {1074 static mock({ addCleanup }) {1075 let mocker = new VSCodeOutputChannelMocker();1076 let originalCreateOutputChannel = vscode.window.createOutputChannel;1077 addCleanup(() => {1078 vscode.window.createOutputChannel = originalCreateOutputChannel;1079 });1080 vscode.window.createOutputChannel = (name) => {1081 return mocker._createOutputChannel(name);1082 };1083 return mocker;1084 }1085 constructor() {1086 this._outputChannels = [];1087 }1088 getOutputChannels() {1089 return [...this._outputChannels];1090 }1091 _createOutputChannel(name) {1092 console.log(1093 `called: vscode.window.createOutputChannel(${JSON.stringify(name)})`1094 );1095 let channel = new FakeOutputChannel(name);1096 this._outputChannels.push(channel);1097 return channel;1098 }1099}1100class FakeOutputChannel /*:: implements vscode.OutputChannel */ {1101 constructor(name) {1102 this._name = name;1103 this._data = "";1104 }1105 get name() {1106 return this._name;1107 }1108 append(value) {1109 this._data += value;1110 }1111 appendLine(value) {1112 this.append(value);1113 this.append("\n");1114 }1115 clear() {1116 this._data = "";1117 }1118 show() {1119 // Ignore.1120 }1121 hide() {1122 // Ignore.1123 }1124 dispose() {}1125}1126function mockInotifyErrors({ addCleanup, addWatchError = 0, initError = 0 }) {1127 qljsExtension.mockInotifyErrors(initError, addWatchError);1128 addCleanup(() => {1129 qljsExtension.mockInotifyErrors(0, 0);1130 });1131}1132function mockKqueueErrors({ addCleanup, directoryOpenError = 0 }) {1133 qljsExtension.mockKqueueErrors(directoryOpenError);1134 addCleanup(() => {1135 qljsExtension.mockKqueueErrors(0);1136 });1137}1138async function causeLogMessagesAsync({ addCleanup }) {1139 let scratchDirectory = makeScratchDirectory({ addCleanup });1140 let jsFilePath = path.join(scratchDirectory, "hello.js");1141 fs.writeFileSync(jsFilePath, "test;");1142 let jsDocument = await vscode.workspace.openTextDocument(1143 vscode.Uri.file(jsFilePath)1144 );1145 let jsEditor = await vscode.window.showTextDocument(1146 jsDocument,1147 vscode.ViewColumn.One1148 );1149 await waitForAsynchronousLogMessagesAsync();1150}1151async function waitForAsynchronousLogMessagesAsync() {1152 await sleepAsync(100);1153}1154// Convert an array of vscode.Diagnostic into an array of plain JavaScript1155// objects. Use this with assert.deepStrictEqual in tests.1156//1157// If given a vscode.Uri, diagnostics are extracted from that document.1158function normalizeDiagnostics(vscodeDiagnosticsOrURI) {1159 let vscodeDiagnostics;1160 if (vscodeDiagnosticsOrURI instanceof vscode.Uri) {1161 vscodeDiagnostics = vscode.languages.getDiagnostics(vscodeDiagnosticsOrURI);1162 } else {1163 vscodeDiagnostics = vscodeDiagnosticsOrURI;1164 }1165 return vscodeDiagnostics.map((diag) => ({1166 code: {1167 target: diag.code.target.toString(true),1168 value: diag.code.value,1169 },1170 message: diag.message,1171 source: diag.source,1172 severity: diag.severity,1173 startLine: diag.range.start.line,1174 startCharacter: diag.range.start.character,1175 endLine: diag.range.end.line,1176 endCharacter: diag.range.end.character,1177 relatedInformation:1178 typeof diag.relatedInformation === "undefined"1179 ? []1180 : diag.relatedInformation.map((info) => ({1181 message: info.message,1182 uri: info.location.uri.toString(),1183 startLine: info.location.range.start.line,1184 startCharacter: info.location.range.start.character,1185 endLine: info.location.range.end.line,1186 endCharacter: info.location.range.end.character,1187 })),1188 }));1189}1190async function loadExtensionAsync({ addCleanup }) {1191 addCleanup(async () => {1192 await qljsExtension.deactivate();1193 });1194 await qljsExtension.activate();1195}1196function makeScratchDirectory({ addCleanup }) {1197 let scratchDirectory = fs.mkdtempSync(1198 path.join(os.tmpdir(), "quick-lint-js-vscode-test-")1199 );1200 addCleanup(() => {1201 fs.rmdirSync(scratchDirectory, { recursive: true });1202 });1203 // TODO(strager): Don't call realpath. realpath is currently needed to work1204 // around bugs in quick-lint-js regarding symlinks.1205 return fs.realpathSync(scratchDirectory);1206}1207function sleepAsync(duration) {1208 return new Promise((resolve, _reject) => {1209 setTimeout(() => {1210 resolve();1211 }, duration);1212 });1213}1214async function pollAsync(callback) {...

Full Screen

Full Screen

topics.js

Source:topics.js Github

copy

Full Screen

...16 * seconds s17 */18const t = require('../../topicsLogger');19// Heizung20t.addLogger({topic:"akm/d01/state/temp01",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});21t.addLogger({topic:"akm/d01/state/temp02",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});22t.addLogger({topic:"akm/d01/state/temp03",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});23t.addLogger({topic:"akm/d01/state/temp04",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});24t.addLogger({topic:"akm/d01/state/temp05",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});25t.addLogger({topic:"akm/d01/state/power01",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});26t.addLogger({topic:"akm/d01/state/power02",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});27t.addLogger({topic:"akm/d01/state/state01",condition:"every",interval:15,newonly:true}).addCleanup({unit:"years",lifespan:10});28t.addLogger({topic:"akm/d01/state/state02",condition:"every",interval:15,newonly:true}).addCleanup({unit:"years",lifespan:10});29t.addLogger({topic:"akm/d01/state/counter01",condition:"every",interval:15,newonly:true}).addCleanup({unit:"years",lifespan:10});30t.addLogger({topic:"akm/d01/state/counter02",condition:"every",interval:15,newonly:true}).addCleanup({unit:"years",lifespan:10});31t.addLogger({topic:"akm/m01/state/power01",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});32t.addLogger({topic:"akm/m01/state/counter01",condition:"every",interval:15,newonly:true}).addCleanup({unit:"years",lifespan:10});33t.addLogger({topic:"akm/m01/state/counter02",condition:"every",interval:15,neonly:true}).addCleanup({unit:"years",lifespan:10});34t.addLogger({topic:"akm/d02/state/temp2",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});35t.addLogger({topic:"akm/d02/state/temp3",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});36// Lueftung37t.addLogger({topic:"akm/d04/state/temp1",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});38t.addLogger({topic:"akm/d04/state/hum1",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});39t.addLogger({topic:"akm/d04/state/temp2",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});40t.addLogger({topic:"akm/d04/state/hum2",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});41t.addLogger({topic:"akm/d05/state/temp01",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});42t.addLogger({topic:"akm/d05/state/hum01",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});43t.addLogger({topic:"akm/d05/state/mode01",condition:"every",interval:15,newonly:true}).addCleanup({unit:"years",lifespan:10});44t.addLogger({topic:"akm/d05/state/mode02",condition:"every",interval:15,newonly:true}).addCleanup({unit:"years",lifespan:10});45t.addLogger({topic:"akm/location/buero/state/temp01",condition:"every",interval:15,newonly:true}).addCleanup({unit:"years",lifespan:10});46t.addLogger({topic:"akm/location/buero/state/hum01",condition:"every",interval:15,newonly:true}).addCleanup({unit:"years",lifespan:10});47// Strom48t.addLogger({topic:"akm/m02/state/power01",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});49t.addLogger({topic:"akm/m02/state/counter01",condition:"every",interval:15,newonly:true}).addCleanup({unit:"years",lifespan:10});50t.addLogger({topic:"akm/m02/state/counter02",condition:"every",interval:15,neonly:true}).addCleanup({unit:"years",lifespan:10});51t.addLogger({topic:"akm/m02/state/counterLastDay01",condition:"all",newonly:true}).addCleanup({unit:"years",lifespan:10});52t.addLogger({topic:"akm/m02/state/counterLastDay02",condition:"all",neonly:true}).addCleanup({unit:"years",lifespan:10});53t.addLogger({topic:"akm/m03/state/counterLastDay01",condition:"all",newonly:true}).addCleanup({unit:"years",lifespan:10});54t.addLogger({topic:"akm/m03/state/counterLastDay02",condition:"all",neonly:true}).addCleanup({unit:"years",lifespan:10});55t.addLogger({topic:"akm/m03/state/power01",condition:"every",interval:15}).addCleanup({unit:"years",lifespan:10});56t.addLogger({topic:"akm/m03/state/counter01",condition:"every",interval:15,newonly:true}).addCleanup({unit:"years",lifespan:10});57t.addLogger({topic:"akm/m03/state/counter02",condition:"every",interval:15,neonly:true}).addCleanup({unit:"years",lifespan:10});58/*59t.addLogger({ topic:"akm/m01/state/power01", // Topic to log60 condition:"every", // Condition: all, every (s), atLeast (s), atMost(s), onEvent (trigger)61 interval:15, // for every, atLeast, atMost62 newonly:false // optional: log only new values63 }).addCleanup({ unit:"years",64 lifespan:265 });66 67t.addLogger({ topic:"akm/m01/state/counter01", // Topic to log68 condition:"every", // Condition: all, every (s), atLeast (s), atMost(s), onEvent (trigger)69 interval:15, // for every, atLeast, atMost70 newonly:false // optional: log only new values71 }).addCleanup({ unit:"years",72 lifespan:273 });74t.addLogger({ topic:"akm/m02/state/power01", // Topic to log75 condition:"every", // Condition: all, every (s), atLeast (s), atMost(s), onEvent (trigger)76 interval:15, // for every, atLeast, atMost77 newonly:false // optional: log only new values78 }).addCleanup({ unit:"years",79 lifespan:280 });81t.addLogger({ topic:"mh/l/h1/state/t02", // Topic to log82 condition:"atLeast", // Condition: all, every (s), atLeast (s), atMost(s), onEvent (trigger)83 interval:5, // for every, atLeast, atMost84 newonly:false // optional: log only new values85 }).addCleanup({ unit:"seconds",86 lifespan:3087 });88t.addLogger({ topic:"mh/l/m01/state/c01", // Topic to log89 condition:"onEvent", // Condition: all, every (s), atLeast (s), atMost(s), onEvent (trigger)90 trigger:"mh/event/timer/",91 newonly:false // optional: log only new values92 }).addCleanup({ unit:"seconds",93 lifespan:3094 });95t.addLogger({topic:"mh/location/raum1/state/humidity",condition:"onEvent",trigger:"mh/location/raum1/state/switch"});96t.addCleanup({topic:"mh/event/timer/seconds",unit:"seconds",lifespan:30});97t.addLogger({topic:"mh/event/timer/dawn",condition:"all"});98t.addLogger({topic:"mh/event/timer/dusk",condition:"all"});...

Full Screen

Full Screen

cleanup.js

Source:cleanup.js Github

copy

Full Screen

...56 });57 });58}59exports.cleanup = cleanup;60function addCleanup(callback) {61 cleanupCallbacks.add(callback);62}63exports.addCleanup = addCleanup;64function removeCleanup(callback) {65 cleanupCallbacks.delete(callback);66}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { addCleanup } from 'react-hooks-testing-library';2import { cleanup } from 'react-hooks-testing-library';3import { addCleanup } from 'react-hooks-testing-library';4import { cleanup } from 'react-hooks-testing-library';5import { addCleanup } from 'react-hooks-testing-library';6import { cleanup } from 'react-hooks-testing-library';7import { addCleanup } from 'react-hooks-testing-library';8import { cleanup } from 'react-hooks-testing-library';9import { addCleanup } from 'react-hooks-testing-library';10import { cleanup } from 'react-hooks-testing-library';11import { addCleanup } from 'react-hooks-testing-library';12import { cleanup } from 'react-hooks-testing-library';13import { addCleanup } from 'react-hooks-testing-library';14import { cleanup } from 'react-hooks-testing-library';15import { addCleanup } from 'react-hooks-testing-library';16import { cleanup } from 'react-hooks-testing-library';17import { add

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook, act } from '@testing-library/react-hooks';2import { useCounter } from './useCounter';3test('useCounter', () => {4 const { result, unmount } = renderHook(() => useCounter());5 act(() => {6 result.current.increment();7 });8 expect(result.current.count).toBe(1);9 unmount();10});11import { useState, useEffect } from 'react';12export const useCounter = () => {13 const [count, setCount] = useState(0);14 const increment = () => setCount(count + 1);15 useEffect(() => {16 document.title = `You clicked ${count} times`;17 });18 return { count, increment };19};20import { renderHook, act } from '@testing-library/react-hooks';21import { useCounter } from './useCounter';22test('useCounter', () => {23 const { result, unmount } = renderHook(() => useCounter());24 act(() => {25 result.current.increment();26 });27 expect(result.current.count).toBe(1);28 unmount();29});30import { useState, useEffect } from 'react';31export const useCounter = () => {32 const [count, setCount] = useState(0);33 const increment = () => setCount(count + 1);34 useEffect(() => {35 document.title = `You clicked ${count} times`;36 });37 return { count, increment };38};39import { renderHook, act } from '@testing-library/react-hooks';40import { useCounter } from './useCounter';41test('useCounter', () => {42 const { result, unmount } = renderHook(() => useCounter());43 act(() => {44 result.current.increment();45 });46 expect(result.current.count).toBe(1);47 unmount();48});49import { useState, useEffect } from 'react';50export const useCounter = () => {51 const [count, setCount] = useState(0);52 const increment = () => setCount(count + 1);53 useEffect(() => {54 document.title = `You clicked ${count} times`;55 });56 return { count, increment };57};

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook, act } from '@testing-library/react-hooks';2import { useCounter } from '../src/useCounter';3test('should increment counter', () => {4 const { result } = renderHook(() => useCounter());5 act(() => {6 result.current.increment();7 });8 expect(result.current.count).toBe(1);9});10test('should decrement counter', () => {11 const { result } = renderHook(() => useCounter());12 act(() => {13 result.current.decrement();14 });15 expect(result.current.count).toBe(-1);16});17test('should reset counter', () => {18 const { result } = renderHook(() => useCounter());19 act(() => {20 result.current.increment();21 });22 expect(result.current.count).toBe(1);23 act(() => {24 result.current.reset();25 });26 expect(result.current.count).toBe(0);27});28test('should increment counter by 2', () => {29 const { result } = renderHook(() => useCounter());30 act(() => {31 result.current.incrementBy(2);32 });33 expect(result.current.count).toBe(2);34});35test('should decrement counter by 2', () => {36 const { result } = renderHook(() => useCounter());37 act(() => {38 result.current.decrementBy(2);39 });40 expect(result.current.count).toBe(-2);41});42test('should increment counter by 2 and then reset', () => {43 const { result } = renderHook(() => useCounter());44 act(() => {45 result.current.incrementBy(2);46 });47 expect(result.current.count).toBe(2);48 act(() => {49 result.current.reset();50 });51 expect(result.current.count).toBe(0);52});53test('should decrement counter by 2 and then reset', () => {54 const { result } = renderHook(() => useCounter());55 act(() => {56 result.current.decrementBy(2);57 });58 expect(result.current.count).toBe(-2);59 act(() => {60 result.current.reset();61 });62 expect(result.current.count).toBe(0);63});64test('should increment counter by 2 and then increment by 1', () => {65 const { result } = renderHook(() => useCounter());66 act(() => {67 result.current.incrementBy(2);68 });69 expect(result.current.count).toBe(2);70 act(() =>

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from '@testing-library/react-hooks';2import { useFetch } from './useFetch';3test('useFetch', async () => {4 const { result, waitForNextUpdate, unmount } = renderHook(() =>5 );6 expect(result.current.status).toBe('loading');7 await waitForNextUpdate();8 expect(result.current.status).toBe('success');9 expect(result.current.data.login).toBe('octocat');10 unmount();11});12import { useEffect, useState } from 'react';13export function useFetch(url) {14 const [data, setData] = useState(null);15 const [status, setStatus] = useState('loading');16 useEffect(() => {17 fetch(url)18 .then(res => res.json())19 .then(data => {20 setData(data);21 setStatus('success');22 });23 }, [url]);24 return { data, status };25}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { cleanup, renderHook } from '@testing-library/react-hooks';2import useCounter from './useCounter';3afterEach(cleanup);4test('should increment counter', () => {5 const { result } = renderHook(() => useCounter());6 const { increment } = result.current;7 act(() => {8 increment();9 });10 expect(result.current.count).toBe(1);11});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from '@testing-library/react-hooks'2import useCounter from './useCounter'3test('should increment counter', () => {4 const { result } = renderHook(() => useCounter())5 const { increment } = result.current6 increment()7 expect(result.current.count).toBe(1)8})9test('should decrement counter', () => {10 const { result } = renderHook(() => useCounter())11 const { decrement } = result.current12 decrement()13 expect(result.current.count).toBe(-1)14})15test('should reset counter', () => {16 const { result } = renderHook(() => useCounter())17 const { increment, reset } = result.current18 increment()19 reset()20 expect(result.current.count).toBe(0)21})22test('should reset counter after 5 seconds', async () => {23 jest.useFakeTimers()24 const { result } = renderHook(() => useCounter())25 const { increment, reset } = result.current26 increment()27 expect(result.current.count).toBe(1)28 reset()29 expect(result.current.count).toBe(0)30 jest.advanceTimersByTime(5000)31 expect(result.current.count).toBe(0)32})33import { useState, useEffect } from 'react'34export default function useCounter() {35 const [count, setCount] = useState(0)36 const increment = () => {37 setCount((prevCount) => prevCount + 1)38 }39 const decrement = () => {40 setCount((prevCount) => prevCount - 1)41 }42 const reset = () => {43 setCount(0)44 }45 useEffect(() => {46 const id = setTimeout(() => {47 reset()48 }, 5000)49 return () => {50 clearTimeout(id)51 }52 }, [count])53 return { count, increment, decrement, reset }54}55import { renderHook } from '@testing-library/react-hooks'56import useCounter from

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook, act } from '@testing-library/react-hooks';2import { useCounter } from './useCounter';3test('increment counter', () => {4 const { result } = renderHook(() => useCounter());5 act(() => {6 result.current.increment();7 });8 expect(result.current.count).toBe(1);9});10test('decrement counter', () => {11 const { result } = renderHook(() => useCounter());12 act(() => {13 result.current.decrement();14 });15 expect(result.current.count).toBe(-1);16});17import { useState, useEffect } from 'react';18export const useCounter = () => {19 const [count, setCount] = useState(0);20 useEffect(() => {21 if (count === 5) {22 setCount(0);23 }24 }, [count]);25 const increment = () => setCount(count + 1);26 const decrement = () => setCount(count - 1);27 return { count, increment, decrement };28};29import { renderHook, act } from '@testing-library/react-hooks';30import { useCounter } from './useCounter';31test('increment counter', () => {32 const { result } = renderHook(() => useCounter());33 act(() => {34 result.current.increment();35 });36 expect(result.current.count).toBe(1);37});38test('decrement counter', () => {39 const { result } = renderHook(() => useCounter());40 act(() => {41 result.current.decrement();42 });43 expect(result.current.count).toBe(-1);44});45import { useState, useEffect } from 'react';46export const useCounter = () => {47 const [count, setCount] = useState(0);48 useEffect(() => {49 if (count === 5) {50 setCount(0);51 }52 }, [count]);53 const increment = () => setCount(count + 1);54 const decrement = () => setCount(count - 1);55 return { count, increment, decrement };56};57import

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook, act } from '@testing-library/react-hooks';2import { addCleanup } from 'react-hooks-testing-library';3import useCounter from './useCounter';4describe('useCounter', () => {5 afterEach(() => {6 addCleanup(() => {7 console.log('cleanup');8 });9 });10 it('should return default initial value', () => {11 const { result } = renderHook(() => useCounter());12 expect(result.current.count).toBe(0);13 });14 it('should increment count by 1', () => {15 const { result } = renderHook(() => useCounter());16 act(() => {17 result.current.increment();18 });19 expect(result.current.count).toBe(1);20 });21 it('should increment count by 2', () => {22 const { result } = renderHook(() => useCounter());23 act(() => {24 result.current.increment();25 result.current.increment();26 });27 expect(result.current.count).toBe(2);28 });29});30import { useState } from 'react';31const useCounter = (initialValue = 0) => {32 const [count, setCount] = useState(initialValue);33 const increment = () => {34 setCount(count + 1);35 };36 return { count, increment };37};38export default useCounter;

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from '@testing-library/react-hooks';2import { act } from 'react-dom/test-utils';3import { useCounter } from '../useCounter';4describe('useCounter', () => {5 it('should increment the counter', () => {6 const { result } = renderHook(() => useCounter());7 act(() => {8 result.current.increment();9 });10 expect(result.current.count).toBe(1);11 });12});13import { useState, useEffect } from 'react';14export const useCounter = () => {15 const [count, setCount] = useState(0);16 useEffect(() => {17 const id = setInterval(() => {18 setCount((prevCount) => prevCount + 1);19 }, 1000);20 return () => clearInterval(id);21 }, []);22 const increment = () => setCount((prevCount) => prevCount + 1);23 return { count, increment };24};

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run testing-library-react-hooks automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful