How to use createTestScheduler method in Jest

Best JavaScript code snippet using jest

module-servers-test.js

Source:module-servers-test.js Github

copy

Full Screen

...31 d: { type: 'SERVERS_REGISTER_REQUEST', data: getEnv() },32 };33 const input = '-a--c--a--';34 const output = '-(b|)';35 const ts = createTestScheduler();36 const source = R(37 ts.createColdObservable(input, values)38 );39 const actual = gameStarts(source, {}, getEnv());40 ts.expectObservable(actual).toBe(output, values);41 ts.flush();42 });43 });44 describe('serverRegisterRequests', () => {45 const now = () => 999;46 const timer = () => Observable.of([1]); // mock Observable.timer47 const store = {48 getState: () => ({49 isHub: false,50 })51 };52 // mock fetch53 const successPost = (url, data) => Observable.create(observer => {54 observer.next({55 servers: {56 'http://x.com': {57 address: 'http://x.com'58 }59 }60 });61 observer.complete();62 });63 it('should register itself with on SERVERS_REGISTER_REQUEST', () => {64 expect.hasAssertions();65 const values = {66 a: {67 type: 'SERVERS_REGISTER_REQUEST',68 data: getEnv(),69 },70 b: {71 type: 'SERVERS_REGISTER_RESPONSE',72 data: {73 servers: {74 'http://x.com': {75 address: 'http://x.com',76 }77 },78 lastUpdated: now(),79 }80 }81 };82 const timer = () => Observable.of([1]); // mock Observable.timer83 const input = '-a-a--a';84 const output = '-b-b--b';85 const ts = createTestScheduler();86 const source = R(ts.createColdObservable(input, values));87 const actual = serverRegisterRequests(88 source, store, successPost, now, timer, 089 );90 ts.expectObservable(actual).toBe(output, values);91 ts.flush();92 });93 it('should no nothing if there is no hub', () => {94 expect.hasAssertions();95 const values = {96 a: {97 type: 'SERVERS_REGISTER_REQUEST',98 data: {},99 },100 };101 const input = '-a';102 const output = '--';103 const ts = createTestScheduler();104 const source = R(ts.createColdObservable(input, values));105 const actual = serverRegisterRequests(106 source, store, successPost, now107 );108 ts.expectObservable(actual).toBe(output, values);109 ts.flush();110 });111 });112 describe('hubServerRegisterRequests ', () => {113 expect.hasAssertions();114 const timer = () => Observable.range(1, 4); // mock Observable.timer115 const now = () => 9999; // mock Observable.timer116 // mock fetch117 const successFetch = (url, data) => Observable.create(observer => {118 observer.next({119 numPlayers: 5,120 maxPlayers: 6,121 numBots: 2,122 address: 'http://x.com',123 location: 'y',124 name: 'z'125 });126 observer.complete();127 });128 const errorFetch = (url, data) => Observable.create(observer => {129 observer.error({130 options: {131 url: 'http://x.com/check'132 }133 });134 observer.complete();135 });136 const store = {137 getState: () => ({138 servers: {},139 })140 };141 it('should check on the servers every X seconds (success)', () => {142 expect.hasAssertions();143 const values = {144 a: {145 type: 'SERVERS_HUB_REGISTRATION_RECEIVED',146 data: {147 address: 'http://x.com',148 },149 },150 b: {151 type: 'SERVERS_HUB_CHECK_SUCCESS',152 data: {153 address: 'http://x.com',154 location: 'y',155 name: 'z',156 lastUpdated: 9999,157 maxPlayers: 6,158 numPlayers: 5,159 numBots: 2,160 },161 },162 };163 const input = '-a----';164 const output = '-(bbbb)';165 const ts = createTestScheduler();166 const source = R(ts.createColdObservable(input, values));167 const actual = hubServerRegisterRequests(source, store, 0, successFetch, timer, now);168 ts.expectObservable(actual).toBe(output, values);169 ts.flush();170 });171 it('should check on the servers every X seconds (error)', () => {172 expect.hasAssertions();173 const values = {174 a: {175 type: 'SERVERS_HUB_REGISTRATION_RECEIVED',176 data: {177 address: 'http://x.com',178 },179 },180 b: {181 type: 'SERVERS_HUB_CHECK_ERROR',182 data: {183 address: 'http://x.com',184 },185 },186 };187 const input = '-a----';188 const output = '-(bbbb)';189 const ts = createTestScheduler();190 const source = R(ts.createColdObservable(input, values));191 const actual = hubServerRegisterRequests(source, store, 0, errorFetch, timer, now);192 ts.expectObservable(actual).toBe(output, values);193 ts.flush();194 });195 });196 });197 describe('reducer', () => {198 const initialStateWithPlayers = {199 players: {},200 bots: { '1': {}, '2': {}},201 ...initialState,202 };203 describe('server', () => {...

Full Screen

Full Screen

Observable unit testing.js

Source:Observable unit testing.js Github

copy

Full Screen

...125))126describe('repeatWhen with scheduler.run', () => {127 let oldValue, scheduler;128 beforeEach(() =>{129 scheduler = createTestScheduler();130 oldValue = ajax.get131 });132 133 afterEach(() => { ajax.get = oldValue;});134 135 it('should repeat initial ajax call in 1 second', () => {136 scheduler.run((helpers) =>{ 137 const { cold, hot, expectObservable } = helpers;138 const valuesMap = {a: 5};139 let mock = cold('a|', valuesMap);140 ajax.get = jasmine.createSpy('ajax.get').and.returnValue(mock);141 142 const expected = "a 1s a 1s a|";143 expectObservable(getData(1)).toBe(expected, valuesMap);144 })145 })146})147// TestScheduler.run with switchMap148let Rx = window['rxjs'];149const {of, 150 defer, 151 queueScheduler,152 asapScheduler,153 asyncScheduler,154 animationFrameScheduler,155 VirtualTimeScheduler} = Rx;156const {switchMap, repeat, tap, filter, debounceTime, distinctUntilChanged} = Rx.operators;157const {TestScheduler} = Rx.testing;158console.clear();159const {ajax} = Rx.ajax;160let makeWikiSearch;161const $input = document.querySelector('#textInput');162const getInputObservable = () => Rx.fromEvent($input, 'keyup').pipe(163 // map(e => e.target.value),164 filter(text => text.length > 2),165 debounceTime(750),166 distinctUntilChanged(),167 switchMap((text) => makeWikiSearch(text))168)169const scheduler = new TestScheduler((actual, expected) => {170 console.log('expected', actual, expected);171 expect(_.isEqual(actual, expected)).toBeTruthy();172});173describe('switchMap', () => {174 let oldValue, oldValue2;175 beforeEach(() =>{176 oldValue = Rx.fromEvent;177 oldValue2 = makeWikiSearch178 });179 180 afterEach(() => {181 Rx.fromEvent = oldValue;182 makeWikiSearch = oldValue2;183 });184 185 it('should repeat initial ajax call in 1 second', () => {186 scheduler.run((helpers) =>{ 187 const { cold, hot, expectObservable, expectSubscriptions, flush } = helpers;188 Rx.fromEvent = () => cold('a 800ms b 700ms c 1700ms |', {a: 'a', b: 'aaa', c: 'aaab'});189 makeWikiSearch = () => cold("(a|)", {a: ['text1','text2','text3']});190 const expected = "2252ms r 950ms |";191 expectObservable(getInputObservable()).toBe(expected, {r: ['text1','text2','text3']});192 })193 })194})195// TestScheduler.run vs TestScheduler196let Rx = window['rxjs'];197const {of, 198 defer, 199 queueScheduler,200 asapScheduler,201 asyncScheduler,202 animationFrameScheduler,203 VirtualTimeScheduler} = Rx;204const {take, repeatWhen, repeat, delay} = Rx.operators;205const {TestScheduler} = Rx.testing;206console.clear();207const {ajax} = Rx.ajax;208const createTestScheduler = () => {209 return new TestScheduler((actual, expected) => {210 console.log('expected', actual, expected);211 expect(_.isEqual(actual, expected)).toBeTruthy();212});213}214const getData = (timeSec) => ajax.get('http://localhost:4001/list-data')215.pipe(216 repeatWhen((notification) => notification.pipe(217 delay(timeSec * 1000),218 take(2)219 )220))221describe('repeatWhen with scheduler.run', () => {222 let oldValue, scheduler;223 beforeEach(() =>{224 scheduler = createTestScheduler();225 oldValue = ajax.get226 });227 228 afterEach(() => { ajax.get = oldValue;});229 230 it('should repeat initial ajax call in 1 second', () => {231 scheduler.run((helpers) =>{ 232 const { cold, hot, expectObservable } = helpers;233 const valuesMap = {a: 5};234 let mock = cold('a|', valuesMap);235 ajax.get = jasmine.createSpy('ajax.get').and.returnValue(mock);236 237 const expected = "a 1s a 1s a|";238 expectObservable(getData(1)).toBe(expected, valuesMap);239 })240 })241})242describe('repeatWhen with testScheduler.flush', () => {243 let oldValue, scheduler;244 beforeEach(() =>{245 scheduler = createTestScheduler();246 oldValue = ajax.get;247 asyncScheduler.constructor.delegate = scheduler;248 });249 250 afterEach(() => {251 ajax.get = oldValue;252 asyncScheduler.constructor.delegate = undefined;253 });254 255 it('should repeat initial ajax call in 1 second', () => {256 scheduler.maxFrames = 10000;257 const valuesMap = {a: 4};258 let mock = scheduler.createColdObservable('(a|)', valuesMap);259 ajax.get = () => mock;...

Full Screen

Full Screen

TestScheduler.test.js

Source:TestScheduler.test.js Github

copy

Full Screen

...29 mockParallelRunner.runTests.mockClear();30 spyShouldRunInBand.mockClear();31});32test('config for reporters supports `default`', async () => {33 const undefinedReportersScheduler = await createTestScheduler(34 {35 reporters: undefined,36 },37 {},38 );39 const numberOfReporters =40 undefinedReportersScheduler._dispatcher._reporters.length;41 const stringDefaultReportersScheduler = await createTestScheduler(42 {43 reporters: ['default'],44 },45 {},46 );47 expect(stringDefaultReportersScheduler._dispatcher._reporters.length).toBe(48 numberOfReporters,49 );50 const defaultReportersScheduler = await createTestScheduler(51 {52 reporters: [['default', {}]],53 },54 {},55 );56 expect(defaultReportersScheduler._dispatcher._reporters.length).toBe(57 numberOfReporters,58 );59 const emptyReportersScheduler = await createTestScheduler(60 {61 reporters: [],62 },63 {},64 );65 expect(emptyReportersScheduler._dispatcher._reporters.length).toBe(0);66});67test('.addReporter() .removeReporter()', async () => {68 const scheduler = await createTestScheduler({}, {});69 const reporter = new SummaryReporter();70 scheduler.addReporter(reporter);71 expect(scheduler._dispatcher._reporters).toContain(reporter);72 scheduler.removeReporter(SummaryReporter);73 expect(scheduler._dispatcher._reporters).not.toContain(reporter);74});75test('schedule tests run in parallel per default', async () => {76 const scheduler = await createTestScheduler({}, {});77 const test = {78 context: {79 config: makeProjectConfig({80 moduleFileExtensions: ['.js'],81 runner: 'jest-runner-parallel',82 transform: [],83 }),84 hasteFS: {85 matchFiles: jest.fn(() => []),86 },87 },88 path: './test/path.js',89 };90 const tests = [test, test];91 await scheduler.scheduleTests(tests, {isInterrupted: jest.fn()});92 expect(mockParallelRunner.runTests).toHaveBeenCalled();93 expect(mockParallelRunner.runTests.mock.calls[0][5].serial).toBeFalsy();94});95test('schedule tests run in serial if the runner flags them', async () => {96 const scheduler = await createTestScheduler({}, {});97 const test = {98 context: {99 config: makeProjectConfig({100 moduleFileExtensions: ['.js'],101 runner: 'jest-runner-serial',102 transform: [],103 }),104 hasteFS: {105 matchFiles: jest.fn(() => []),106 },107 },108 path: './test/path.js',109 };110 const tests = [test, test];111 await scheduler.scheduleTests(tests, {isInterrupted: jest.fn()});112 expect(mockSerialRunner.runTests).toHaveBeenCalled();113 expect(mockSerialRunner.runTests.mock.calls[0][5].serial).toBeTruthy();114});115test('should bail after `n` failures', async () => {116 const scheduler = await createTestScheduler({bail: 2}, {});117 const test = {118 context: {119 config: makeProjectConfig({120 moduleFileExtensions: ['.js'],121 rootDir: './',122 runner: 'jest-runner-serial',123 transform: [],124 }),125 hasteFS: {126 matchFiles: jest.fn(() => []),127 },128 },129 path: './test/path.js',130 };131 const tests = [test];132 const setState = jest.fn();133 await scheduler.scheduleTests(tests, {134 isInterrupted: jest.fn(),135 isWatchMode: () => true,136 setState,137 });138 await mockSerialRunner.runTests.mock.calls[0][3](test, {139 numFailingTests: 2,140 snapshot: {},141 testResults: [{}],142 });143 expect(setState).toBeCalledWith({interrupted: true});144});145test('should not bail if less than `n` failures', async () => {146 const scheduler = await createTestScheduler({bail: 2}, {});147 const test = {148 context: {149 config: makeProjectConfig({150 moduleFileExtensions: ['.js'],151 rootDir: './',152 runner: 'jest-runner-serial',153 transform: [],154 }),155 hasteFS: {156 matchFiles: jest.fn(() => []),157 },158 },159 path: './test/path.js',160 };161 const tests = [test];162 const setState = jest.fn();163 await scheduler.scheduleTests(tests, {164 isInterrupted: jest.fn(),165 isWatchMode: () => true,166 setState,167 });168 await mockSerialRunner.runTests.mock.calls[0][3](test, {169 numFailingTests: 1,170 snapshot: {},171 testResults: [{}],172 });173 expect(setState).not.toBeCalled();174});175test('should set runInBand to run in serial', async () => {176 const scheduler = await createTestScheduler({}, {});177 const test = {178 context: {179 config: makeProjectConfig({180 moduleFileExtensions: ['.js'],181 runner: 'jest-runner-parallel',182 transform: [],183 }),184 hasteFS: {185 matchFiles: jest.fn(() => []),186 },187 },188 path: './test/path.js',189 };190 const tests = [test, test];191 spyShouldRunInBand.mockReturnValue(true);192 await scheduler.scheduleTests(tests, {isInterrupted: jest.fn()});193 expect(spyShouldRunInBand).toHaveBeenCalled();194 expect(mockParallelRunner.runTests).toHaveBeenCalled();195 expect(mockParallelRunner.runTests.mock.calls[0][5].serial).toBeTruthy();196});197test('should set runInBand to not run in serial', async () => {198 const scheduler = await createTestScheduler({}, {});199 const test = {200 context: {201 config: makeProjectConfig({202 moduleFileExtensions: ['.js'],203 runner: 'jest-runner-parallel',204 transform: [],205 }),206 hasteFS: {207 matchFiles: jest.fn(() => []),208 },209 },210 path: './test/path.js',211 };212 const tests = [test, test];...

Full Screen

Full Screen

module-bots-test.js

Source:module-bots-test.js Github

copy

Full Screen

...35 c: { type: 'UNKNOWN_ACTION' },36 };37 const input = 'c--a--c';38 const output = '---(bbbbb)'; // add 5 bots on game start39 const ts = createTestScheduler();40 const source = R(ts.createColdObservable(input, values));41 const actual = addBots(source, store, env, getPos, getId);42 ts.expectObservable(actual).toBe(output, values);43 ts.flush();44 });45 it('should persist a bot and player to the state on ADD_BOT', () => {46 const resultState1 = reducer({ players: {}, bots: {} }, {47 type: 'ADD_BOT',48 origin: 'server',49 data: {50 playerId: '1',51 x: 20,52 y: 30,53 }54 });55 expect(resultState1).toEqual({56 players: {57 '1': {58 alive: true, id: '1', name: `Bot 1`, frags: 0, deaths: 0,59 x: 20, y: 30, isBot: true,60 },61 },62 bots: {63 '1': {64 id: '1', target: null,65 }66 },67 });68 const resultState2 = reducer(resultState1, {69 type: 'ADD_BOT',70 origin: 'server',71 data: {72 playerId: '2',73 x: 30,74 y: 40,75 }76 });77 expect(resultState2).toEqual({78 players: {79 '1': {80 alive: true, id: '1', name: `Bot 1`, frags: 0, deaths: 0,81 x: 20, y: 30, isBot: true,82 },83 '2': {84 alive: true, id: '2', name: `Bot 2`, frags: 0, deaths: 0,85 x: 30, y: 40, isBot: true,86 },87 },88 bots: {89 '1': {90 id: '1', target: null,91 },92 '2': {93 id: '2', target: null,94 },95 },96 });97 });98 it('should set the target after adding a bot', () => {99 const timer = () => Observable.range(1, 2); // mock Observable.timer100 // mock the random id generator so it returns 0 or 1101 let nextId = 0;102 const random = () => {103 nextId = nextId === 1 ? 0 : 1;104 return nextId;105 };106 // note: setTargets will call random twice for every ADD_BOT, once to107 // add time108 const store = ({109 getState: () => ({110 players: {111 '1': {112 name: 'Player 1'113 },114 '2': {115 name: 'Player 2'116 },117 }118 })119 });120 const values = {121 a: {122 type: 'ADD_BOT',123 origin: 'server',124 data: { playerId: '5', x: 10, y: 10 }125 },126 b: {127 type: 'SET_TARGET',128 origin: 'server',129 data: { playerId: '1', botId: '5' }130 },131 c: {132 type: 'SET_TARGET',133 origin: 'server',134 data: { playerId: '2', botId: '5' }135 },136 };137 const input = '---a---';138 const output = '---(bc)';139 const ts = createTestScheduler();140 const source = R(ts.createColdObservable(input, values));141 const actual = setTargets(source, store, random, timer);142 ts.expectObservable(actual).toBe(output, values);143 ts.flush();144 });145 it('should persist the target when the target it set', () => {146 // todo147 });148 it('should find a new target when the target is dead', () => {149 // todo150 });151 it('should find a new target when the target leaves', () => {152 // todo153 });...

Full Screen

Full Screen

epic.test.js

Source:epic.test.js Github

copy

Full Screen

...18} from "../boards/actions";19import { rootReducer } from "../configureStore";20import { coordinates } from "../boards/test/testData";21it("successful initialization", () => {22 createTestScheduler().run(({ hot, cold, expectObservable }) => {23 const action$ = hot("-a----b", {24 a: initialize(),25 b: webSocketConnectionOpened()26 });27 const state$ = cold("|");28 const user = { id: 1, name: "lovely taylor" };29 const dependencies = {30 ajax: {31 post: (url = "/api/auth") =>32 cold("---a|", {33 a: { response: user }34 }),35 get: (url = "/api/boards") =>36 cold("---a|", {37 a: { response: [] }38 })39 }40 };41 const output$ = epic(action$, state$, dependencies);42 expectObservable(output$).toBe("----ab---cd", {43 a: authenticated(user),44 b: openWebSocketConnection(),45 c: activeBoardListLoaded([]),46 d: initializationSuccessful()47 });48 });49});50it("failed authentication", () => {51 createTestScheduler().run(({ hot, cold, expectObservable }) => {52 const action$ = hot("-a", {53 a: initialize()54 });55 const state$ = cold("|");56 const dependencies = {57 ajax: {58 post: (url = "/api/auth") => cold("---#")59 }60 };61 const output$ = epic(action$, state$, dependencies);62 expectObservable(output$).toBe("----a", {63 a: initializationFailed()64 });65 });66});67it("failed boards fetch", () => {68 createTestScheduler().run(({ hot, cold, expectObservable }) => {69 const action$ = hot("-a", {70 a: webSocketConnectionOpened()71 });72 const state$ = cold("|");73 const dependencies = {74 ajax: {75 get: (url = "/api/boards") => cold("---#")76 }77 };78 const output$ = epic(action$, state$, dependencies);79 expectObservable(output$).toBe("----a", {80 a: initializationFailed()81 });82 });83});84it("dirty board reload", () => {85 createTestScheduler().run(({ hot, cold, expectObservable }) => {86 const action$ = hot("--a", {87 a: activeBoardListLoaded([])88 });89 const state = [90 activeBoardListLoaded([{ id: 1, moves: [] }]),91 enterBoard(1),92 activeBoardListLoaded([])93 ].reduce(rootReducer, undefined);94 const state$ = hot("-a", { a: state });95 state$.value = state;96 const finishedBoard = {97 id: 1,98 winner: { userId: 2 }99 };100 const dependencies = {101 ajax: {102 get: (url = "/api/boards/{boardId}") =>103 cold("---a|", {104 a: { response: finishedBoard }105 })106 }107 };108 const output$ = epic(action$, state$, dependencies);109 expectObservable(output$).toBe("-----a", {110 a: finishedBoardLoaded(finishedBoard)111 });112 });113});114it("should not reload finished board", () => {115 createTestScheduler().run(({ hot, cold, expectObservable }) => {116 const action$ = hot("--a", {117 a: activeBoardListLoaded([])118 });119 const state = [120 activeBoardListLoaded([{ id: 1, moves: [] }]),121 enterBoard(1),122 playerWonMessage(1, { coordinates: coordinates(0, 0) }, { userId: 1 }),123 activeBoardListLoaded([])124 ].reduce(rootReducer, undefined);125 const state$ = hot("-a", { a: state });126 state$.value = state;127 const dependencies = {128 ajax: {}129 };...

Full Screen

Full Screen

news.epics.test.js

Source:news.epics.test.js Github

copy

Full Screen

...6import { createTestScheduler, stateEpic } from '../../../setupTests'; 7test('fetchNewsEpic success', () => {8 const marbles1 = 'a-';9 const marbles2 = '-b';10 const ts = createTestScheduler();11 const response = { response: {} };12 const duration = ts.createTime('-|');13 const state$ = stateEpic;14 const ajax = () => of(response).pipe(delay(duration, ts));15 const values = {16 a: actions.fetchNewsAction(),17 b: actions.fetchNewsSuccessAction(response.response),18 };19 const source = ActionsObservable.from(20 ts.createColdObservable(marbles1, values),21 );22 const actual = epics.fetchNewsEpic(source, state$, { ajax });23 ts.expectObservable(actual).toBe(marbles2, values);24 ts.flush();25});26test('fetchNewsEpic error', () => {27 const marbles1 = 'a-';28 const marbles2 = '-b';29 const ts = createTestScheduler();30 const duration = ts.createTime('-|');31 const state$ = stateEpic;32 const ajax = () => of({}).pipe(delay(duration, ts), mergeMap(() => throwError({})));33 const values = {34 a: actions.fetchNewsAction(),35 b: actions.fetchNewsErrorAction(),36 };37 const source = ActionsObservable.from(38 ts.createColdObservable(marbles1, values),39 );40 const actual = epics.fetchNewsEpic(source, state$, { ajax });41 ts.expectObservable(actual).toBe(marbles2, values);42 ts.flush();43});44test('setNewsPageEpic', () => {45 const marbles1 = 'a';46 const marbles2 = 'b';47 const ts = createTestScheduler();48 const values = {49 a: actions.setNewsPageAction(1),50 b: actions.fetchNewsAction(),51 };52 const source = ActionsObservable.from(53 ts.createColdObservable(marbles1, values),54 );55 const actual = epics.setNewsPageEpic(source);56 ts.expectObservable(actual).toBe(marbles2, values);57 ts.flush();58});59test('setNewsFilterEpic', () => {60 const marbles1 = 'a';61 const marbles2 = '(bc)';62 const ts = createTestScheduler();63 const values = {64 a: actions.setNewsFilterAction(),65 b: actions.resetNewsAction(),66 c: actions.setNewsPageAction(0),67 };68 const source = ActionsObservable.from(69 ts.createColdObservable(marbles1, values),70 );71 const actual = epics.setNewsFilterEpic(source);72 ts.expectObservable(actual).toBe(marbles2, values);73 ts.flush();...

Full Screen

Full Screen

epics.spec.js

Source:epics.spec.js Github

copy

Full Screen

...20 totalPoints: 17,21 },22});23it("updates profile successfully", () => {24 createTestScheduler().run(({ hot, cold, expectObservable }) => {25 const state$ = hot("ss", {26 s: createState(),27 });28 const action$ = hot("-a", { a: createAction(updateProfile.type) });29 updateProfile$.mockReturnValue(cold("--r"));30 const output$ = updateProfileEpic(action$, state$);31 expectObservable(output$).toBe("---a", {32 a: createAction(updateProfileFulfilled.type),33 });34 });35});36it("updates profile unsuccessfully", () => {37 createTestScheduler().run(({ hot, cold, expectObservable }) => {38 const state$ = hot("ss", {39 s: createState(),40 });41 const action$ = hot("-a", { a: createAction(updateProfile.type) });42 updateProfile$.mockReturnValue(cold("--#"));43 const output$ = updateProfileEpic(action$, state$);44 expectObservable(output$).toBe("---a", {45 a: createAction(updateProfileFailed.type, { error: "error" }),46 });47 });...

Full Screen

Full Screen

index.spec.js

Source:index.spec.js Github

copy

Full Screen

...3import { filter, mapTo, shareReplay, takeUntil } from "rxjs/operators";45describe("dataOrDefault", () => {6 it("should emit the default value if no success within 5 frames", () => {7 const testScheduler = createTestScheduler();8 testScheduler.run(({ expectObservable, cold }) => {9 // prettier-ignore10 const streams = {11 data$: "p------s-",12 expected$: "p----D-s-"13 }14 expectObservable(dataOrDefault(testScheduler, cold(streams.data$))).toBe(15 streams.expected$16 );17 });18 });1920 it("should NOT emit the default value if success is received soon", () => {21 const testScheduler = createTestScheduler();22 testScheduler.run(({ expectObservable, cold }) => {23 // prettier-ignore24 const streams = {25 data$: "p--s----",26 expected$: "p--s----"27 }28 expectObservable(dataOrDefault(testScheduler, cold(streams.data$))).toBe(29 streams.expected$30 );31 });32 });33});3435function dataOrDefault(testScheduler, data$) { ...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest 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