Best JavaScript code snippet using tracetest
unittest.test.ts
Source:unittest.test.ts
1'use strict';2import * as assert from 'assert';3import * as fs from 'fs-extra';4import * as path from 'path';5import { anything, instance, mock, when } from 'ts-mockito';6import { ConfigurationTarget } from 'vscode';7import { EXTENSION_ROOT_DIR } from '../../../client/common/constants';8import { EnvironmentActivationService } from '../../../client/interpreter/activation/service';9import { IEnvironmentActivationService } from '../../../client/interpreter/activation/types';10import { ICondaService, IInterpreterService } from '../../../client/interpreter/contracts';11import { InterpreterService } from '../../../client/interpreter/interpreterService';12import { CondaService } from '../../../client/pythonEnvironments/discovery/locators/services/condaService';13import { CommandSource } from '../../../client/testing/common/constants';14import { ITestManagerFactory, TestFile, TestFunction, Tests, TestsToRun } from '../../../client/testing/common/types';15import { rootWorkspaceUri, updateSetting } from '../../common';16import { UnitTestIocContainer } from '../serviceRegistry';17import { initialize, initializeTest, IS_MULTI_ROOT_TEST } from './../../initialize';18const testFilesPath = path.join(EXTENSION_ROOT_DIR, 'src', 'test', 'pythonFiles', 'testFiles');19const UNITTEST_TEST_FILES_PATH = path.join(testFilesPath, 'standard');20const UNITTEST_SINGLE_TEST_FILE_PATH = path.join(testFilesPath, 'single');21const UNITTEST_MULTI_TEST_FILE_PATH = path.join(testFilesPath, 'multi');22const UNITTEST_COUNTS_TEST_FILE_PATH = path.join(testFilesPath, 'counter');23const defaultUnitTestArgs = ['-v', '-s', '.', '-p', '*test*.py'];24// tslint:disable-next-line:max-func-body-length25suite('Unit Tests - unittest - discovery against actual python process', () => {26 let ioc: UnitTestIocContainer;27 const configTarget = IS_MULTI_ROOT_TEST ? ConfigurationTarget.WorkspaceFolder : ConfigurationTarget.Workspace;28 suiteSetup(async () => {29 await initialize();30 await updateSetting('testing.unittestArgs', defaultUnitTestArgs, rootWorkspaceUri!, configTarget);31 });32 setup(async () => {33 const cachePath = path.join(UNITTEST_TEST_FILES_PATH, '.cache');34 if (await fs.pathExists(cachePath)) {35 await fs.remove(cachePath);36 }37 await initializeTest();38 initializeDI();39 });40 teardown(async () => {41 await ioc.dispose();42 await updateSetting('testing.unittestArgs', defaultUnitTestArgs, rootWorkspaceUri!, configTarget);43 });44 function initializeDI() {45 ioc = new UnitTestIocContainer();46 ioc.registerCommonTypes();47 ioc.registerVariableTypes();48 ioc.registerUnitTestTypes();49 ioc.registerProcessTypes();50 ioc.registerInterpreterStorageTypes();51 ioc.registerMockInterpreterTypes();52 ioc.serviceManager.rebindInstance<ICondaService>(ICondaService, instance(mock(CondaService)));53 ioc.serviceManager.rebindInstance<IInterpreterService>(IInterpreterService, instance(mock(InterpreterService)));54 const mockEnvironmentActivationService = mock(EnvironmentActivationService);55 when(mockEnvironmentActivationService.getActivatedEnvironmentVariables(anything())).thenResolve();56 when(mockEnvironmentActivationService.getActivatedEnvironmentVariables(anything(), anything())).thenResolve();57 when(58 mockEnvironmentActivationService.getActivatedEnvironmentVariables(anything(), anything(), anything())59 ).thenResolve();60 ioc.serviceManager.rebindInstance<IEnvironmentActivationService>(61 IEnvironmentActivationService,62 instance(mockEnvironmentActivationService)63 );64 }65 test('Discover Tests (single test file)', async () => {66 await updateSetting('testing.unittestArgs', ['-s=./tests', '-p=test_*.py'], rootWorkspaceUri!, configTarget);67 const factory = ioc.serviceContainer.get<ITestManagerFactory>(ITestManagerFactory);68 const testManager = factory('unittest', rootWorkspaceUri!, UNITTEST_SINGLE_TEST_FILE_PATH);69 const tests = await testManager.discoverTests(CommandSource.ui, true, true);70 assert.equal(tests.testFiles.length, 1, 'Incorrect number of test files');71 assert.equal(tests.testFunctions.length, 3, 'Incorrect number of test functions');72 assert.equal(tests.testSuites.length, 1, 'Incorrect number of test suites');73 assert.equal(74 tests.testFiles.some((t) => t.name === 'test_one.py' && t.nameToRun === 'test_one'),75 true,76 'Test File not found'77 );78 assert.equal(79 tests.testFunctions.some(80 (t) => t.testFunction.name === 'test_A' && t.testFunction.nameToRun === 'test_one.Test_test1.test_A'81 ),82 true,83 'Test File not found'84 );85 });86 test('Discover Tests (many test files, subdir included)', async () => {87 await updateSetting('testing.unittestArgs', ['-s=./tests', '-p=test_*.py'], rootWorkspaceUri!, configTarget);88 const factory = ioc.serviceContainer.get<ITestManagerFactory>(ITestManagerFactory);89 const testManager = factory('unittest', rootWorkspaceUri!, UNITTEST_MULTI_TEST_FILE_PATH);90 const tests = await testManager.discoverTests(CommandSource.ui, true, true);91 assert.equal(tests.testFiles.length, 3, 'Incorrect number of test files');92 assert.equal(tests.testFunctions.length, 9, 'Incorrect number of test functions');93 assert.equal(tests.testSuites.length, 3, 'Incorrect number of test suites');94 assert.equal(95 tests.testFiles.some((t) => t.name === 'test_one.py' && t.nameToRun === 'test_one'),96 true,97 'Test File one not found'98 );99 assert.equal(100 tests.testFiles.some((t) => t.name === 'test_two.py' && t.nameToRun === 'test_two'),101 true,102 'Test File two not found'103 );104 assert.equal(105 tests.testFiles.some((t) => t.name === 'test_three.py' && t.nameToRun === 'more_tests.test_three'),106 true,107 'Test File three not found'108 );109 assert.equal(110 tests.testFunctions.some(111 (t) => t.testFunction.name === 'test_A' && t.testFunction.nameToRun === 'test_one.Test_test1.test_A'112 ),113 true,114 'Test File one not found'115 );116 assert.equal(117 tests.testFunctions.some(118 (t) => t.testFunction.name === 'test_2A' && t.testFunction.nameToRun === 'test_two.Test_test2.test_2A'119 ),120 true,121 'Test File two not found'122 );123 assert.equal(124 tests.testFunctions.some(125 (t) =>126 t.testFunction.name === 'test_3A' &&127 t.testFunction.nameToRun === 'more_tests.test_three.Test_test3.test_3A'128 ),129 true,130 'Test File three not found'131 );132 });133 test('Run single test', async () => {134 await updateSetting('testing.unittestArgs', ['-s=./tests', '-p=test_*.py'], rootWorkspaceUri!, configTarget);135 const factory = ioc.serviceContainer.get<ITestManagerFactory>(ITestManagerFactory);136 const testManager = factory('unittest', rootWorkspaceUri!, UNITTEST_MULTI_TEST_FILE_PATH);137 const testsDiscovered: Tests = await testManager.discoverTests(CommandSource.ui, true, true);138 const testFile: TestFile | undefined = testsDiscovered.testFiles.find((value: TestFile) =>139 value.nameToRun.endsWith('_three')140 );141 assert.notEqual(testFile, undefined, 'No test file suffixed with _3A in test files.');142 assert.equal(testFile!.suites.length, 1, 'Expected only 1 test suite in test file three.');143 const testFunc: TestFunction | undefined = testFile!.suites[0].functions.find(144 (value: TestFunction) => value.name === 'test_3A'145 );146 assert.notEqual(testFunc, undefined, 'No test in file test_three.py named test_3A');147 const testsToRun: TestsToRun = {148 testFunction: [testFunc!]149 };150 const testRunResult: Tests = await testManager.runTest(CommandSource.ui, testsToRun);151 assert.equal(152 testRunResult.summary.failures + testRunResult.summary.passed + testRunResult.summary.skipped,153 1,154 'Expected to see only 1 test run in the summary for tests run.'155 );156 assert.equal(testRunResult.summary.errors, 0, 'Unexpected: Test file ran with errors.');157 assert.equal(testRunResult.summary.failures, 0, 'Unexpected: Test has failed during test run.');158 assert.equal(159 testRunResult.summary.passed,160 1,161 `Only one test should have passed during our test run. Instead, ${testRunResult.summary.passed} passed.`162 );163 assert.equal(164 testRunResult.summary.skipped,165 0,166 `Expected to have skipped 0 tests during this test-run. Instead, ${testRunResult.summary.skipped} where skipped.`167 );168 });169 test('Ensure correct test count for running a set of tests multiple times', async function () {170 // https://github.com/microsoft/vscode-python/issues/11634171 // tslint:disable-next-line: no-invalid-this172 return this.skip();173 await updateSetting('testing.unittestArgs', ['-s=./tests', '-p=test_*.py'], rootWorkspaceUri!, configTarget);174 const factory = ioc.serviceContainer.get<ITestManagerFactory>(ITestManagerFactory);175 const testManager = factory('unittest', rootWorkspaceUri!, UNITTEST_COUNTS_TEST_FILE_PATH);176 const testsDiscovered: Tests = await testManager.discoverTests(CommandSource.ui, true, true);177 const testsFile: TestFile | undefined = testsDiscovered.testFiles.find((value: TestFile) =>178 value.name.startsWith('test_unit_test_counter')179 );180 assert.notEqual(181 testsFile,182 undefined,183 `No test file suffixed with _counter in test files. Looked in ${UNITTEST_COUNTS_TEST_FILE_PATH}.`184 );185 assert.equal(testsFile!.suites.length, 1, 'Expected only 1 test suite in counter test file.');186 const testsToRun: TestsToRun = {187 testFolder: [testsDiscovered.testFolders[0]]188 };189 // ensure that each re-run of the unit tests in question result in the same summary count information.190 let testRunResult: Tests = await testManager.runTest(CommandSource.ui, testsToRun);191 assert.equal(192 testRunResult.summary.failures,193 2,194 'This test was written assuming there was 2 tests run that would fail. (iteration 1)'195 );196 assert.equal(197 testRunResult.summary.passed,198 2,199 'This test was written assuming there was 2 tests run that would succeed. (iteration 1)'200 );201 testRunResult = await testManager.runTest(CommandSource.ui, testsToRun);202 assert.equal(203 testRunResult.summary.failures,204 2,205 'This test was written assuming there was 2 tests run that would fail. (iteration 2)'206 );207 assert.equal(208 testRunResult.summary.passed,209 2,210 'This test was written assuming there was 2 tests run that would succeed. (iteration 2)'211 );212 });213 test('Re-run failed tests results in the correct number of tests counted', async function () {214 // https://github.com/microsoft/vscode-python/issues/11634215 // tslint:disable-next-line: no-invalid-this216 return this.skip();217 await updateSetting('testing.unittestArgs', ['-s=./tests', '-p=test_*.py'], rootWorkspaceUri!, configTarget);218 const factory = ioc.serviceContainer.get<ITestManagerFactory>(ITestManagerFactory);219 const testManager = factory('unittest', rootWorkspaceUri!, UNITTEST_COUNTS_TEST_FILE_PATH);220 const testsDiscovered: Tests = await testManager.discoverTests(CommandSource.ui, true, true);221 const testsFile: TestFile | undefined = testsDiscovered.testFiles.find((value: TestFile) =>222 value.name.startsWith('test_unit_test_counter')223 );224 assert.notEqual(225 testsFile,226 undefined,227 `No test file suffixed with _counter in test files. Looked in ${UNITTEST_COUNTS_TEST_FILE_PATH}.`228 );229 assert.equal(testsFile!.suites.length, 1, 'Expected only 1 test suite in counter test file.');230 const testsToRun: TestsToRun = {231 testFolder: [testsDiscovered.testFolders[0]]232 };233 // ensure that each re-run of the unit tests in question result in the same summary count information.234 let testRunResult: Tests = await testManager.runTest(CommandSource.ui, testsToRun);235 assert.equal(236 testRunResult.summary.failures,237 2,238 'This test was written assuming there was 2 tests run that would fail. (iteration 1)'239 );240 assert.equal(241 testRunResult.summary.passed,242 2,243 'This test was written assuming there was 2 tests run that would succeed. (iteration 1)'244 );245 testRunResult = await testManager.runTest(CommandSource.ui, testsToRun, true);246 assert.equal(247 testRunResult.summary.failures,248 2,249 'This test was written assuming there was 2 tests run that would fail. (iteration 2)'250 );251 });...
trx-generator.ts
Source:trx-generator.ts
1import {2 AggregatedResult,3 AssertionResult,4 TestResult,5} from "@jest/test-result";6import * as path from "path";7import { v4 as uuidv4 } from "uuid";8import { create as createXmlBuilder, XMLElement } from "xmlbuilder";9import {10 testListAllLoadedResultsId,11 testListNotInListId,12 testOutcomeTable,13 testType,14} from "./constants";15import {16 formatDuration,17 getEnvInfo,18 getFullTestName,19 getTestClassName,20} from "./utils";21/**22 * All the configuration options.23 */24export interface IOptions {25 /**26 * Path to the resulting TRX file.27 * @default "test-results.trx"28 */29 outputFile: string;30 /**31 * The username to use if the real username cannot be detected.32 * @default "anonymous"33 */34 defaultUserName?: string;35 /**36 * Set of methods that may be used to augment the resulting trx file.37 * Each of these methods are called after the testResultNode has been generated.38 */39 postProcessTestResult?: [40 (41 testSuiteResult: TestResult,42 testResult: AssertionResult,43 testResultNode: XMLElement,44 ) => void,45 ];46}47const renderTestRun = (48 builder: XMLElement,49 testRunResult: AggregatedResult,50 computerName: string,51 userName: string,52): void => {53 builder54 .att("id", uuidv4())55 .att(56 "name",57 `${userName}@${computerName} ${new Date(58 testRunResult.startTime,59 ).toISOString()}`,60 )61 .att("runUser", userName)62 .att("xmlns", "http://microsoft.com/schemas/VisualStudio/TeamTest/2010");63};64const renderTestSettings = (parentNode: XMLElement): void => {65 parentNode66 .ele("TestSettings")67 .att("name", "Jest test run")68 .att("id", uuidv4());69};70const renderTimes = (71 parentNode: XMLElement,72 testRunResult: AggregatedResult,73): void => {74 const startTime = new Date(testRunResult.startTime).toISOString();75 parentNode76 .ele("Times")77 .att("creation", startTime)78 .att("queuing", startTime)79 .att("start", startTime)80 .att("finish", startTime);81};82const renderResultSummary = (83 parentNode: XMLElement,84 testRunResult: AggregatedResult,85): void => {86 // workaround for https://github.com/facebook/jest/issues/692487 const anyTestFailures = !(88 testRunResult.numFailedTests === 0 &&89 testRunResult.numRuntimeErrorTestSuites === 090 );91 const isSuccess = !(anyTestFailures || testRunResult.snapshot.failure);92 const summary = parentNode93 .ele("ResultSummary")94 .att("outcome", isSuccess ? "Passed" : "Failed");95 summary96 .ele("Counters")97 .att(98 "total",99 testRunResult.numTotalTests + testRunResult.numRuntimeErrorTestSuites,100 )101 .att(102 "executed",103 testRunResult.numTotalTests - testRunResult.numPendingTests,104 )105 .att("passed", testRunResult.numPassedTests)106 .att("failed", testRunResult.numFailedTests)107 .att("error", testRunResult.numRuntimeErrorTestSuites);108};109const renderTestLists = (parentNode: XMLElement): void => {110 const testLists = parentNode.ele("TestLists");111 testLists112 .ele("TestList")113 .att("name", "Results Not in a List")114 .att("id", testListNotInListId);115 testLists116 .ele("TestList")117 .att("name", "All Loaded Results")118 .att("id", testListAllLoadedResultsId);119};120const renderTestSuiteResult = (121 testSuiteResult: TestResult,122 testDefinitionsNode: XMLElement,123 testEntriesNode: XMLElement,124 resultsNode: XMLElement,125 computerName: string,126 postProcessTestResult?: [127 (128 // eslint-disable-next-line no-shadow129 testSuiteResult: TestResult,130 testResult: AssertionResult,131 testResultNode: XMLElement,132 ) => void,133 ],134): void => {135 if (testSuiteResult.testResults && testSuiteResult.testResults.length) {136 let runningDuration = 0;137 testSuiteResult.testResults.forEach((testResult) => {138 const testId = uuidv4();139 const executionId = uuidv4();140 const fullTestName = getFullTestName(testResult);141 const filepath = path.relative("./", testSuiteResult.testFilePath);142 const duration = testResult.duration || 0;143 // UnitTest144 const unitTest = testDefinitionsNode145 .ele("UnitTest")146 .att("name", fullTestName)147 .att("id", testId)148 .att("storage", filepath);149 unitTest.ele("Execution").att("id", executionId);150 unitTest151 .ele("TestMethod")152 .att("codeBase", filepath)153 .att("name", fullTestName)154 .att("className", getTestClassName(testResult));155 // TestEntry156 testEntriesNode157 .ele("TestEntry")158 .att("testId", testId)159 .att("executionId", executionId)160 .att("testListId", testListNotInListId);161 // UnitTestResult162 const result = resultsNode163 .ele("UnitTestResult")164 .att("testId", testId)165 .att("executionId", executionId)166 .att("testName", fullTestName)167 .att("computerName", computerName)168 .att("duration", formatDuration(duration))169 .att(170 "startTime",171 new Date(172 testSuiteResult.perfStats.start,173 ).toISOString(),174 )175 .att(176 "endTime",177 new Date(178 testSuiteResult.perfStats.start + runningDuration,179 ).toISOString(),180 )181 .att("testType", testType)182 .att("outcome", testOutcomeTable[testResult.status])183 .att("testListId", testListNotInListId);184 runningDuration += duration;185 if (testResult.status === "failed") {186 result187 .ele("Output")188 .ele("ErrorInfo")189 .ele("Message", testResult.failureMessages.join("\n"));190 }191 // Perform any post processing for this test result.192 if (postProcessTestResult) {193 postProcessTestResult.forEach(postProcess =>194 postProcess(testSuiteResult, testResult, result),195 );196 }197 });198 }199 if (testSuiteResult.testExecError?.stack) {200 // For suites that failed to run, we will generate a test result that documents the failure.201 // This occurs when there is a failure compiling/loading the suite or an assertion in a before/after hook fails,202 // not when a test in the suite fails.203 const testId = uuidv4();204 const executionId = uuidv4();205 const fullTestName = path.basename(testSuiteResult.testFilePath);206 const time = new Date().toISOString();207 const filepath = path.relative("./", testSuiteResult.testFilePath);208 // Failed TestSuite209 const unitTest = testDefinitionsNode210 .ele("UnitTest")211 .att("name", fullTestName)212 .att("id", testId)213 .att("storage", filepath);214 unitTest.ele("Execution").att("id", executionId);215 unitTest216 .ele("TestMethod")217 .att("codeBase", filepath)218 .att("name", fullTestName)219 .att("className", fullTestName);220 // TestEntry221 testEntriesNode222 .ele("TestEntry")223 .att("testId", testId)224 .att("executionId", executionId)225 .att("testListId", testListNotInListId);226 // UnitTestResult227 const result = resultsNode228 .ele("UnitTestResult")229 .att("testId", testId)230 .att("executionId", executionId)231 .att("testName", fullTestName)232 .att("computerName", computerName)233 .att("duration", "0")234 .att("startTime", time)235 .att("endTime", time)236 .att("testType", testType)237 .att("outcome", testOutcomeTable.failed)238 .att("testListId", testListNotInListId);239 result240 .ele("Output")241 .ele("ErrorInfo")242 .ele("Message", testSuiteResult.testExecError.stack);243 }244};245export const generateTrx = (246 testRunResult: AggregatedResult,247 options?: IOptions,248): string => {249 const { computerName, userName } = getEnvInfo(250 options && options.defaultUserName,251 );252 const resultBuilder = createXmlBuilder("TestRun", {253 invalidCharReplacement: "",254 version: "1.0",255 encoding: "UTF-8",256 });257 renderTestRun(resultBuilder, testRunResult, computerName, userName);258 renderTestSettings(resultBuilder);259 renderTimes(resultBuilder, testRunResult);260 renderResultSummary(resultBuilder, testRunResult);261 const testDefinitions = resultBuilder.ele("TestDefinitions");262 renderTestLists(resultBuilder);263 const testEntries = resultBuilder.ele("TestEntries");264 const results = resultBuilder.ele("Results");265 testRunResult.testResults.forEach(testSuiteResult =>266 renderTestSuiteResult(267 testSuiteResult,268 testDefinitions,269 testEntries,270 results,271 computerName,272 options && options.postProcessTestResult,273 ),274 );275 return resultBuilder.end({ pretty: true });...
recording.test.js
Source:recording.test.js
1import Recording from "../classes/Recording";2import TestRunResult from "../classes/TestRunResult";3import uuid from "uuid";4import axios from "axios";5import * as dynamoDbLib from "../libs/dynamodb-lib";6jest.mock("../libs/dynamodb-lib");7jest.mock("axios");8// jest.mock("../classes/TestRunResult");9beforeEach(() => {10 dynamoDbLib.call.mockClear();11 axios.mockClear();12});13describe("constructor", () => {14 const json = {15 userId: uuid.v1(),16 steps: ["foo", "bar"],17 location: { foo: "bar" },18 code: `test test`,19 cookies: ["coo", "kie"],20 isAuthFlow: false,21 // shouldn't construct with:22 recordingId: undefined,23 createdAt: undefined,24 results: undefined,25 nextScheduledTest: undefined26 };27 const recording = new Recording(json);28 test("returns correct instance", () => {29 expect(recording).toBeInstanceOf(Recording);30 });31 test("constructs with correct user supplied properties", () => {32 expect(recording).toHaveProperty("code", json.code);33 expect(recording).toHaveProperty("cookies", json.cookies);34 expect(recording).toHaveProperty("debugCode", json.debugCode);35 expect(recording).toHaveProperty("isAuthFlow", json.isAuthFlow);36 expect(recording).toHaveProperty("location", json.location);37 expect(recording).toHaveProperty("steps", json.steps);38 expect(recording).toHaveProperty("userId", json.userId);39 });40 test("doesn't set user supplied values for automatically set properties", () => {41 expect(recording.recordingId).toBeDefined();42 expect(recording.createdAt).toBeDefined();43 expect(recording.results).toBeDefined();44 expect(recording.nextScheduledTest).toBeDefined();45 });46});47describe("#from", () => {48 const date = new Date();49 date.setDate(date.getDate() - 1);50 const json = {51 recordingId: uuid.v1(),52 userId: uuid.v1(),53 results: ["foo", "bar"],54 createdAt: date,55 nextScheduledTest: new Date(),56 isActive: false57 };58 const recording = Recording.from(json);59 test("returns an instance", () => {60 expect(recording).toBeInstanceOf(Recording);61 });62 test("returns correct properties", () => {63 expect(recording).toEqual({64 authedCookies: null,65 code: undefined,66 cookies: undefined,67 createdAt: date,68 debugCode: undefined,69 isActive: json.isActive,70 isAuthFlow: undefined,71 location: undefined,72 nextScheduledTest: json.nextScheduledTest,73 recordingId: json.recordingId,74 results: json.results,75 steps: undefined,76 userId: json.userId77 });78 });79});80describe("#updateNextScheduledTest", () => {81 const json = {82 recordingId: uuid.v1(),83 userId: uuid.v1()84 };85 const recording = new Recording(json);86 test("called with correct params", () => {87 recording.updateNextScheduledTest();88 expect(dynamoDbLib.call).toHaveBeenCalledWith("update", {89 ExpressionAttributeValues: {90 ":nextScheduledTest": recording.nextScheduledTest91 },92 Key: {93 recordingId: recording.recordingId,94 userId: recording.userId95 },96 TableName: undefined,97 UpdateExpression: "SET nextScheduledTest = :nextScheduledTest"98 });99 });100});101describe("#query", () => {102 Recording.query({ userId: "foo" });103 expect(dynamoDbLib.call).toHaveBeenCalledWith("query", {104 ExpressionAttributeValues: { ":userId": "foo" },105 KeyConditionExpression: "userId = :userId",106 TableName: undefined107 });108});109describe("#get", () => {110 const json = {111 userId: uuid.v1()112 };113 const recording = new Recording(json);114 recording.get();115 expect(dynamoDbLib.call).toHaveBeenCalledWith("get", {116 Key: {117 recordingId: recording.recordingId,118 userId: recording.userId119 },120 TableName: undefined121 });122});123describe("#execute", () => {124 const json = {125 userId: uuid.v1(),126 location: {}127 };128 let recording = new Recording(json);129 const axiosResponse = {130 data: { error: null, stepResults: [], authedCookies: ["authed", "cookies"] }131 };132 axios.mockResolvedValue(axiosResponse);133 const mockedUpdateCookies = jest.fn();134 Recording.prototype._updateCookies = mockedUpdateCookies;135 const mockedAddResult = jest.fn();136 Recording.prototype._addResult = mockedAddResult;137 const mockedUpdateAuthFlow = jest.fn();138 Recording.prototype._updateAuthFlow = mockedUpdateAuthFlow;139 const mockedTestRunResult = new TestRunResult({140 error: null,141 authedCookies: ["authed", "cookies"],142 stepResults: []143 });144 const mockedBuildTestRunResult = jest.fn();145 TestRunResult.build = mockedBuildTestRunResult;146 mockedBuildTestRunResult.mockResolvedValue(mockedTestRunResult);147 const mockedTestRunResultFrom = jest.fn();148 TestRunResult.from = mockedTestRunResultFrom;149 mockedTestRunResultFrom.mockResolvedValue(mockedTestRunResultFrom);150 beforeEach(() => {151 Recording.prototype._updateCookies.mockClear();152 Recording.prototype._addResult.mockClear();153 Recording.prototype._updateAuthFlow.mockClear();154 TestRunResult.build.mockClear();155 TestRunResult.from.mockClear();156 });157 test("if the recording !isAuthFlow", async () => {158 recording = new Recording({ isAuthFlow: false });159 expect(recording.isAuthFlow).toBeFalsy();160 await recording.execute();161 expect(recording._updateCookies).toHaveBeenCalled();162 });163 test("if the recording isAuthFlow", async () => {164 recording = new Recording({ isAuthFlow: true });165 expect(recording.isAuthFlow).toBeTruthy();166 await recording.execute();167 expect(recording._updateCookies).not.toHaveBeenCalled();168 });169 describe("chrome api call", () => {170 test("gets called with authCookies if present", async () => {171 recording = new Recording();172 recording.authedCookies = ["auth", "cookies"];173 await recording.execute();174 expect(axios).toHaveBeenCalledWith(175 expect.objectContaining({176 data: {177 code: undefined,178 context: { cookies: recording.authedCookies }179 }180 })181 );182 });183 test("gets called with code", async () => {184 recording = new Recording({ code: "some sick code" });185 await recording.execute();186 expect(axios).toHaveBeenCalledWith(187 expect.objectContaining({188 data: {189 code: recording.code,190 context: { cookies: recording.cookies }191 }192 })193 );194 });195 test("builds a TestRunResult", async () => {196 recording = new Recording();197 await recording.execute();198 expect(TestRunResult.build).toHaveBeenCalledWith(axiosResponse);199 });200 test("builds a TestRunResult with correct error when axios call errors", async () => {201 recording = new Recording();202 const error = { data: "it broke" };203 axios.mockImplementationOnce(() => {204 throw new Error(error);205 });206 await recording.execute();207 expect(TestRunResult.from).toHaveBeenCalledWith({208 data: { error: undefined }209 });210 });211 });212 test("calls _addResult", async () => {213 recording = new Recording();214 await recording.execute();215 expect(recording._addResult).toHaveBeenCalledWith(mockedTestRunResult);216 });217 describe("if it is an auth flow", () => {218 beforeEach(async () => {219 Recording.prototype._updateAuthFlow.mockClear();220 recording = new Recording({221 userId: uuid.v1(),222 isAuthFlow: true223 });224 await recording.execute();225 });226 test("it calls _updateAuthFlow", () => {227 expect(recording._updateAuthFlow).toHaveBeenCalledWith(228 mockedTestRunResult229 );230 });231 test("it sets authedCookies", () => {232 expect(recording.authedCookies).toEqual(["authed", "cookies"]);233 });234 });235 describe("if it is not an auth flow", () => {236 beforeEach(async () => {237 Recording.prototype._updateAuthFlow.mockClear();238 recording = new Recording({239 userId: uuid.v1(),240 isAuthFlow: false241 });242 await recording.execute();243 });244 test("it does not call _updateAuthFlow", () => {245 expect(recording._updateAuthFlow).not.toHaveBeenCalled();246 });247 test("it does not set authedCookies", () => {248 expect(recording.authedCookies).toEqual(null);249 });250 });...
Using AI Code Generation
1var tracetest = require('tracetest');2tracetest.testRunResult();3var tracetest = require('tracetest');4tracetest.testRunResult();5var tracetest = require('tracetest');6tracetest.testRunResult();7var tracetest = require('tracetest');8tracetest.testRunResult();9var tracetest = require('tracetest');10tracetest.testRunResult();11var tracetest = require('tracetest');12tracetest.testRunResult();13var tracetest = require('tracetest');14tracetest.testRunResult();15var tracetest = require('tracetest');16tracetest.testRunResult();17var tracetest = require('tracetest');18tracetest.testRunResult();19var tracetest = require('tracetest');20tracetest.testRunResult();21var tracetest = require('tracetest');22tracetest.testRunResult();23var tracetest = require('tracetest');24tracetest.testRunResult();25var tracetest = require('tracetest');26tracetest.testRunResult();27var tracetest = require('tracetest');28tracetest.testRunResult();29var tracetest = require('tracetest');30tracetest.testRunResult();31var tracetest = require('tracetest');32tracetest.testRunResult();
Using AI Code Generation
1var tracetest = require('./tracetest.js');2tracetest.testRunResult();3exports.testRunResult = function() {4 console.log('testRunResult');5}6var tracetest = require('/home/username/tracetest.js');
Using AI Code Generation
1const tracetest = require('tracetest');2tracetest.testRunResult('test1', test1);3tracetest.testRunResult('test2', test2);4tracetest.testRunResult('test3', test3);5const tracetest = require('tracetest');6tracetest.testRunResult('test1', test1);7tracetest.testRunResult('test2', test2);8tracetest.testRunResult('test3', test3);9const tracetest = require('tracetest');10tracetest.testRunResult('test1', test1);11tracetest.testRunResult('test2', test2);12tracetest.testRunResult('test3', test3);13const tracetest = require('tracetest');14tracetest.testRunResult('test1', test1);15tracetest.testRunResult('test2', test2);16tracetest.testRunResult('test3', test3);17const tracetest = require('tracetest');18tracetest.testRunResult('test1', test1);19tracetest.testRunResult('test2', test2);20tracetest.testRunResult('test3', test3);21const tracetest = require('tracetest');22tracetest.testRunResult('test1', test1);23tracetest.testRunResult('test2', test2);24tracetest.testRunResult('test3', test3);25const tracetest = require('tracetest');26tracetest.testRunResult('test1', test1);27tracetest.testRunResult('test2', test2);28tracetest.testRunResult('test3', test3);29const tracetest = require('tracetest');30tracetest.testRunResult('test1', test1);31tracetest.testRunResult('test2', test2);32tracetest.testRunResult('test3', test3);
Using AI Code Generation
1var tracetest = require('tracetest');2tracetest.testRunResult('test', 'test');3var tracetest = require('tracetest');4tracetest.testRunResult('test', 'test');5var tracetest = require('tracetest');6tracetest.testRunResult('test', 'test');7var tracetest = require('tracetest');8tracetest.testRunResult('test', 'test');9var tracetest = require('tracetest');10tracetest.testRunResult('test', 'test');11var tracetest = require('tracetest');12tracetest.testRunResult('test', 'test');13var tracetest = require('tracetest');14tracetest.testRunResult('test', 'test');15var tracetest = require('tracetest');16tracetest.testRunResult('test', 'test');17var tracetest = require('tracetest');18tracetest.testRunResult('test', 'test');19var tracetest = require('tracetest');20tracetest.testRunResult('test', 'test');21var tracetest = require('tracetest');22tracetest.testRunResult('test', 'test');23var tracetest = require('tracetest');24tracetest.testRunResult('test', 'test');
Using AI Code Generation
1var tracetest = require('tracetest');2var result = tracetest.testRunResult();3console.log('result: ' + result);4var tracetest = require('tracetest');5var result = tracetest.testRunResult();6console.log('result: ' + result);
Using AI Code Generation
1var testRunResult = require('./tracetest.js').testRunResult;2testRunResult('Test case 1', 1, 1);3testRunResult('Test case 2', 1, 2);4exports.testRunResult = function(testName, actual, expected){5 if(actual === expected){6 console.log('PASSED: ' + testName);7 }else{8 console.log('FAILED: ' + testName + ' Expected ' + expected + ', but got ' + actual);9 }10}
Using AI Code Generation
1var tracetest = require('tracetest');2tracetest.testRunResult(1, 1, 'Test Case 1', 'Test Case 1 passed');3tracetest.testRunResult(1, 0, 'Test Case 2', 'Test Case 2 failed');4var tracetest = require('tracetest');5tracetest.testRunResult(1, 1, 'Test Case 1', 'Test Case 1 passed');6tracetest.testRunResult(1, 0, 'Test Case 2', 'Test Case 2 failed');7var tracetest = require('tracetest');8tracetest.testRunResult(1, 1, 'Test Case 1', 'Test Case 1 passed');9tracetest.testRunResult(1, 0, 'Test Case 2', 'Test Case 2 failed');10var tracetest = require('tracetest');11tracetest.testRunResult(1, 1, 'Test Case 1', 'Test Case 1 passed');12tracetest.testRunResult(1, 0, 'Test Case 2', 'Test Case 2 failed');13var tracetest = require('tracetest');14tracetest.testRunResult(1, 1, 'Test Case 1', 'Test Case 1 passed');15tracetest.testRunResult(1, 0, 'Test Case 2', 'Test Case 2 failed');16var tracetest = require('tracetest');17tracetest.testRunResult(1, 1, 'Test Case 1', 'Test Case 1 passed');18tracetest.testRunResult(1, 0, 'Test Case 2', 'Test Case 2 failed');19var tracetest = require('tracetest');
Using AI Code Generation
1var tracetest = require('tracetest');2tracetest.testRunResult('test.js', 'testRunResult', 'testRunResult', 1, 1);3var tracetest = require('tracetest');4tracetest.testRunResult('test.js', 'testRunResult', 'testRunResult', 1, 1);5var tracetest = require('tracetest');6tracetest.testRunResult('test.js', 'testRunResult', 'testRunResult', 1, 1);7var tracetest = require('tracetest');8tracetest.testRunResult('test.js', 'testRunResult', 'testRunResult', 1, 1);9var tracetest = require('tracetest');10tracetest.testRunResult('test.js', 'testRunResult', 'testRunResult', 1, 1);11var tracetest = require('tracetest');12tracetest.testRunResult('test.js', 'testRunResult', 'testRunResult', 1, 1);13var tracetest = require('tracetest');14tracetest.testRunResult('test.js', 'testRunResult', 'testRunResult', 1, 1);15var tracetest = require('tracetest');16tracetest.testRunResult('test.js', 'testRunResult', 'testRunResult', 1, 1);17var tracetest = require('tracetest');18tracetest.testRunResult('test.js', 'testRunResult', 'testRunResult', 1, 1);
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!