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

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

TestHarness.js

Source:TestHarness.js Github

copy

Full Screen

1/*2 * Copyright (C) 2015-2017 Apple Inc. All rights reserved.3 *4 * Redistribution and use in source and binary forms, with or without5 * modification, are permitted provided that the following conditions6 * are met:7 *8 * 1. Redistributions of source code must retain the above copyright9 * notice, this list of conditions and the following disclaimer.10 * 2. Redistributions in binary form must reproduce the above copyright11 * notice, this list of conditions and the following disclaimer in the12 * documentation and/or other materials provided with the distribution.13 *14 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED16 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE17 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY18 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES19 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;20 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND21 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.24 */25TestHarness = class TestHarness extends WI.Object26{27 constructor()28 {29 super();30 this._logCount = 0;31 this._failureObjects = new Map;32 this._failureObjectIdentifier = 1;33 // Options that are set per-test for debugging purposes.34 this.forceDebugLogging = false;35 // Options that are set per-test to ensure deterministic output.36 this.suppressStackTraces = false;37 }38 completeTest()39 {40 throw new Error("Must be implemented by subclasses.");41 }42 addResult()43 {44 throw new Error("Must be implemented by subclasses.");45 }46 debugLog()47 {48 throw new Error("Must be implemented by subclasses.");49 }50 // If 'callback' is a function, it will be with the arguments51 // callback(error, result, wasThrown). Otherwise, a promise is52 // returned that resolves with 'result' or rejects with 'error'.53 // The options object accepts the following keys and values:54 // 'remoteObjectOnly': if true, do not unwrap the result payload to a55 // primitive value even if possible. Useful if testing WI.RemoteObject directly.56 evaluateInPage(string, callback, options={})57 {58 throw new Error("Must be implemented by subclasses.");59 }60 debug()61 {62 throw new Error("Must be implemented by subclasses.");63 }64 createAsyncSuite(name)65 {66 return new AsyncTestSuite(this, name);67 }68 createSyncSuite(name)69 {70 return new SyncTestSuite(this, name);71 }72 get logCount()73 {74 return this._logCount;75 }76 log(message)77 {78 ++this._logCount;79 if (this.forceDebugLogging)80 this.debugLog(message);81 else82 this.addResult(message);83 }84 json(object, filter)85 {86 this.log(JSON.stringify(object, filter || null, 2));87 }88 assert(condition, message)89 {90 if (condition)91 return;92 let stringifiedMessage = TestHarness.messageAsString(message);93 this.log("ASSERT: " + stringifiedMessage);94 }95 expectThat(actual, message)96 {97 this._expect(TestHarness.ExpectationType.True, !!actual, message, actual);98 }99 expectTrue(actual, message)100 {101 this._expect(TestHarness.ExpectationType.True, !!actual, message, actual);102 }103 expectFalse(actual, message)104 {105 this._expect(TestHarness.ExpectationType.False, !actual, message, actual);106 }107 expectNull(actual, message)108 {109 this._expect(TestHarness.ExpectationType.Null, actual === null, message, actual, null);110 }111 expectNotNull(actual, message)112 {113 this._expect(TestHarness.ExpectationType.NotNull, actual !== null, message, actual);114 }115 expectEqual(actual, expected, message)116 {117 this._expect(TestHarness.ExpectationType.Equal, expected === actual, message, actual, expected);118 }119 expectNotEqual(actual, expected, message)120 {121 this._expect(TestHarness.ExpectationType.NotEqual, expected !== actual, message, actual, expected);122 }123 expectShallowEqual(actual, expected, message)124 {125 this._expect(TestHarness.ExpectationType.ShallowEqual, Object.shallowEqual(actual, expected), message, actual, expected);126 }127 expectNotShallowEqual(actual, expected, message)128 {129 this._expect(TestHarness.ExpectationType.NotShallowEqual, !Object.shallowEqual(actual, expected), message, actual, expected);130 }131 expectEqualWithAccuracy(actual, expected, accuracy, message)132 {133 console.assert(typeof expected === "number");134 console.assert(typeof actual === "number");135 this._expect(TestHarness.ExpectationType.EqualWithAccuracy, Math.abs(expected - actual) <= accuracy, message, actual, expected, accuracy);136 }137 expectLessThan(actual, expected, message)138 {139 this._expect(TestHarness.ExpectationType.LessThan, actual < expected, message, actual, expected);140 }141 expectLessThanOrEqual(actual, expected, message)142 {143 this._expect(TestHarness.ExpectationType.LessThanOrEqual, actual <= expected, message, actual, expected);144 }145 expectGreaterThan(actual, expected, message)146 {147 this._expect(TestHarness.ExpectationType.GreaterThan, actual > expected, message, actual, expected);148 }149 expectGreaterThanOrEqual(actual, expected, message)150 {151 this._expect(TestHarness.ExpectationType.GreaterThanOrEqual, actual >= expected, message, actual, expected);152 }153 pass(message)154 {155 let stringifiedMessage = TestHarness.messageAsString(message);156 this.log("PASS: " + stringifiedMessage);157 }158 fail(message)159 {160 let stringifiedMessage = TestHarness.messageAsString(message);161 this.log("FAIL: " + stringifiedMessage);162 }163 // Use this to expect an exception. To further examine the exception,164 // chain onto the result with .then() and add your own test assertions.165 // The returned promise is rejected if an exception was not thrown.166 expectException(work)167 {168 if (typeof work !== "function")169 throw new Error("Invalid argument to catchException: work must be a function.");170 let expectAndDumpError = (e) => {171 this.expectNotNull(e, "Should produce an exception.");172 if (e)173 this.log(e.toString());174 }175 let error = null;176 let result = null;177 try {178 result = work();179 } catch (caughtError) {180 error = caughtError;181 } finally {182 // If 'work' returns a promise, it will settle (resolve or reject) by itself.183 // Invert the promise's settled state to match the expectation of the caller.184 if (result instanceof Promise) {185 return result.then((resolvedValue) => {186 expectAndDumpError(null);187 return Promise.reject(resolvedValue);188 }, (e) => { // Don't chain the .catch as it will log the value we just rejected.189 expectAndDumpError(e);190 return Promise.resolve(e);191 });192 }193 // If a promise is not produced, turn the exception into a resolved promise, and a194 // resolved value into a rejected value (since an exception was expected).195 expectAndDumpError(error);196 return error ? Promise.resolve(error) : Promise.reject(result);197 }198 }199 // Protected200 static messageAsString(message)201 {202 if (message instanceof Element)203 return message.textContent;204 return typeof message !== "string" ? JSON.stringify(message) : message;205 }206 static sanitizeURL(url)207 {208 if (!url)209 return "(unknown)";210 let lastPathSeparator = Math.max(url.lastIndexOf("/"), url.lastIndexOf("\\"));211 let location = lastPathSeparator > 0 ? url.substr(lastPathSeparator + 1) : url;212 if (!location.length)213 location = "(unknown)";214 // Clean up the location so it is bracketed or in parenthesis.215 if (url.indexOf("[native code]") !== -1)216 location = "[native code]";217 return location;218 }219 static sanitizeStackFrame(frame, i)220 {221 // Most frames are of the form "functionName@file:///foo/bar/File.js:345".222 // But, some frames do not have a functionName. Get rid of the file path.223 let nameAndURLSeparator = frame.indexOf("@");224 let frameName = nameAndURLSeparator > 0 ? frame.substr(0, nameAndURLSeparator) : "(anonymous)";225 let lastPathSeparator = Math.max(frame.lastIndexOf("/"), frame.lastIndexOf("\\"));226 let frameLocation = lastPathSeparator > 0 ? frame.substr(lastPathSeparator + 1) : frame;227 if (!frameLocation.length)228 frameLocation = "unknown";229 // Clean up the location so it is bracketed or in parenthesis.230 if (frame.indexOf("[native code]") !== -1)231 frameLocation = "[native code]";232 else233 frameLocation = "(" + frameLocation + ")";234 return `#${i}: ${frameName} ${frameLocation}`;235 }236 sanitizeStack(stack)237 {238 if (this.suppressStackTraces)239 return "(suppressed)";240 if (!stack || typeof stack !== "string")241 return "(unknown)";242 return stack.split("\n").map(TestHarness.sanitizeStackFrame).join("\n");243 }244 // Private245 _expect(type, condition, message, ...values)246 {247 console.assert(values.length > 0, "Should have an 'actual' value.");248 if (!message || !condition) {249 values = values.map(this._expectationValueAsString.bind(this));250 message = message || this._expectationMessageFormat(type).format(...values);251 }252 if (condition) {253 this.pass(message);254 return;255 }256 message += "\n Expected: " + this._expectedValueFormat(type).format(...values.slice(1));257 message += "\n Actual: " + values[0];258 this.fail(message);259 }260 _expectationValueAsString(value)261 {262 let instanceIdentifier = (object) => {263 let id = this._failureObjects.get(object);264 if (!id) {265 id = this._failureObjectIdentifier++;266 this._failureObjects.set(object, id);267 }268 return "#" + id;269 };270 const maximumValueStringLength = 200;271 const defaultValueString = String(new Object); // [object Object]272 // Special case for numbers, since JSON.stringify converts Infinity and NaN to null.273 if (typeof value === "number")274 return value;275 try {276 let valueString = JSON.stringify(value);277 if (valueString.length <= maximumValueStringLength)278 return valueString;279 } catch { }280 try {281 let valueString = String(value);282 if (valueString === defaultValueString && value.constructor && value.constructor.name !== "Object")283 return value.constructor.name + " instance " + instanceIdentifier(value);284 return valueString;285 } catch {286 return defaultValueString;287 }288 }289 _expectationMessageFormat(type)290 {291 switch (type) {292 case TestHarness.ExpectationType.True:293 return "expectThat(%s)";294 case TestHarness.ExpectationType.False:295 return "expectFalse(%s)";296 case TestHarness.ExpectationType.Null:297 return "expectNull(%s)";298 case TestHarness.ExpectationType.NotNull:299 return "expectNotNull(%s)";300 case TestHarness.ExpectationType.Equal:301 return "expectEqual(%s, %s)";302 case TestHarness.ExpectationType.NotEqual:303 return "expectNotEqual(%s, %s)";304 case TestHarness.ExpectationType.ShallowEqual:305 return "expectShallowEqual(%s, %s)";306 case TestHarness.ExpectationType.NotShallowEqual:307 return "expectNotShallowEqual(%s, %s)";308 case TestHarness.ExpectationType.EqualWithAccuracy:309 return "expectEqualWithAccuracy(%s, %s, %s)";310 case TestHarness.ExpectationType.LessThan:311 return "expectLessThan(%s, %s)";312 case TestHarness.ExpectationType.LessThanOrEqual:313 return "expectLessThanOrEqual(%s, %s)";314 case TestHarness.ExpectationType.GreaterThan:315 return "expectGreaterThan(%s, %s)";316 case TestHarness.ExpectationType.GreaterThanOrEqual:317 return "expectGreaterThanOrEqual(%s, %s)";318 default:319 console.error("Unknown TestHarness.ExpectationType type: " + type);320 return null;321 }322 }323 _expectedValueFormat(type)324 {325 switch (type) {326 case TestHarness.ExpectationType.True:327 return "truthy";328 case TestHarness.ExpectationType.False:329 return "falsey";330 case TestHarness.ExpectationType.NotNull:331 return "not null";332 case TestHarness.ExpectationType.NotEqual:333 case TestHarness.ExpectationType.NotShallowEqual:334 return "not %s";335 case TestHarness.ExpectationType.EqualWithAccuracy:336 return "%s +/- %s";337 case TestHarness.ExpectationType.LessThan:338 return "less than %s";339 case TestHarness.ExpectationType.LessThanOrEqual:340 return "less than or equal to %s";341 case TestHarness.ExpectationType.GreaterThan:342 return "greater than %s";343 case TestHarness.ExpectationType.GreaterThanOrEqual:344 return "greater than or equal to %s";345 default:346 return "%s";347 }348 }349};350TestHarness.ExpectationType = {351 True: Symbol("expect-true"),352 False: Symbol("expect-false"),353 Null: Symbol("expect-null"),354 NotNull: Symbol("expect-not-null"),355 Equal: Symbol("expect-equal"),356 NotEqual: Symbol("expect-not-equal"),357 ShallowEqual: Symbol("expect-shallow-equal"),358 NotShallowEqual: Symbol("expect-not-shallow-equal"),359 EqualWithAccuracy: Symbol("expect-equal-with-accuracy"),360 LessThan: Symbol("expect-less-than"),361 LessThanOrEqual: Symbol("expect-less-than-or-equal"),362 GreaterThan: Symbol("expect-greater-than"),363 GreaterThanOrEqual: Symbol("expect-greater-than-or-equal"),...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

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

Full Screen

Using AI Code Generation

copy

Full Screen

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

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook, act } from "@testing-library/react-hooks";2import { useCounter } from "./useCounter";3describe("useCounter", () => {4 it("should increment value", () => {5 const { result } = renderHook(() => useCounter());6 act(() => {7 result.current.increment();8 });9 expect(result.current.count).toBe(1);10 });11 it("should decrement value", () => {12 const { result } = renderHook(() => useCounter());13 act(() => {14 result.current.decrement();15 });16 expect(result.current.count).toBe(-1);17 });18 it("should reset value", () => {19 const { result } = renderHook(() => useCounter());20 act(() => {21 result.current.increment();22 result.current.reset();23 });24 expect(result.current.count).toBe(0);25 });26});27import { renderHook, act } from "@testing-library/react-hooks";28import { useFetch } from "./useFetch";29describe("useFetch", () => {30 it("should fetch data", async () => {31 const { result, waitForNextUpdate } = renderHook(() =>32 );33 expect(result.current.response).toBe(null);34 expect(result.current.loading).toBe(true);35 await waitForNextUpdate();36 expect(result.current.response).not.toBe(null);37 expect(result.current.loading).toBe(false);38 });39});40import { renderHook } from "@testing-library/react-hooks";41import { useFetch } from "./useFetch";42describe("useFetch", () => {43 it("should fetch data", async () => {44 const { result, waitForNextUpdate } = renderHook(() =>45 );46 expect(result.current.response).toBe(null);47 expect(result.current.loading).toBe(true);48 await waitForNextUpdate();49 expect(result.current.response).not.toBe(null);50 expect(result.current.loading).toBe(false);51 });52});

Full Screen

Using AI Code Generation

copy

Full Screen

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

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(0));5 result.current.increment();6 expect(result.current.count).toBe(1);7});8test('should decrement counter', () => {9 const { result } = renderHook(() => useCounter(0));10 result.current.decrement();11 expect(result.current.count).toBe(-1);12});13test('should reset counter', () => {14 const { result } = renderHook(() => useCounter(0));15 result.current.increment();16 result.current.reset();17 expect(result.current.count).toBe(0);18});19import { renderHook } from '@testing-library/react-hooks';20import { useCounter } from './useCounter';21let result;22beforeEach(() => {23 const { rerender } = renderHook(() => useCounter(0));24 result = rerender();25});26test('should increment counter', () => {27 result.current.increment();28 expect(result.current.count).toBe(1);29});30test('should decrement counter', () => {31 result.current.decrement();32 expect(result.current.count).toBe(-1);33});34test('should reset counter', () => {35 result.current.increment();36 result.current.reset();37 expect(result.current.count).toBe(0);38});39import React from 'react';40import { render } from '@testing-library/react';41import { useCounter } from './useCounter';42import { useCounterWithReducer } from './useCounterWithReducer';43const Counter = ({ initialCount, hook }) => {44 const { count, increment, decrement, reset } = hook(initialCount);45 return (46 <div>Count: {count}</div>47 <button onClick={increment}>Increment</button>48 <button onClick={decrement}>Decrement</button>49 <button onClick={reset}>Reset</button>50 );51};52test('should increment counter', () => {53 const { getByText } = render(<Counter hook={useCounter} />);54 const incrementButton = getByText('Increment');55 const count = getByText('Count: 0

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from '@testing-library/react-hooks';2import { useCounter } from './useCounter';3describe('useCounter', () => {4 it('should increment the counter', () => {5 const { result } = renderHook(() => useCounter());6 expect(result.current.count).toBe(0);7 act(() => result.current.increment());8 expect(result.current.count).toBe(1);9 });10});11import { useCounter } from './useCounter';12describe('useCounter', () => {13 it('should increment the counter', () => {14 const { result } = renderHook(() => useCounter());15 expect(result.current.count).toBe(0);16 act(() => result.current.increment());17 expect(result.current.count).toBe(1);18 });19});20import { renderHook } from '@testing-library/react-hooks';21import { useCounter } from './useCounter';22describe('useCounter', () => {23 it('should increment the counter', () => {24 const { result } = renderHook(() => useCounter());25 expect(result.current.count).toBe(0);26 act(() => result.current.increment());27 expect(result.current.count).toBe(1);28 });29});30import React from 'react';31import { renderHook, act } from '@testing-library/react-hooks';32import { useCounter } from './useCounter';33describe('useCounter', () => {34 it('should increment the counter', () => {35 const { result } = renderHook(() => useCounter());36 expect(result.current.count).toBe(0);37 act(() => result.current.increment());38 expect(result.current.count).toBe(1);39 });40});41import React from 'react';42import { renderHook, act } from '@testing-library/react-hooks';43import { useCounter } from './useCounter';44describe('useCounter',

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