How to use hasAssertions method in Jest

Best JavaScript code snippet using jest

printer.test.js

Source:printer.test.js Github

copy

Full Screen

...34 describe("toLink()", () => {35 test.each(graphQLEntityType)(36 "returns markdown link for GraphQL %s",37 (type) => {38 expect.hasAssertions();39 const entityName = `Test${capitalize(type)}`;40 jest41 .spyOn(graphql, `is${capitalize(type)}Type`)42 .mockReturnValueOnce(true);43 jest.spyOn(graphql, "getNamedType").mockReturnValue(entityName);44 const link = printerInstance.toLink(type, entityName);45 expect(link).toMatchFile(46 path.join(EXPECT_PATH, `toLinkWith${capitalize(type)}.md`),47 );48 },49 );50 test("returns markdown link surrounded by [] for GraphQL list/array", () => {51 expect.hasAssertions();52 const type = "list";53 const subtype = "object";54 const entityName = "TestObjectList";55 jest.spyOn(graphql, "isListType").mockReturnValue(true);56 jest57 .spyOn(graphql, `is${capitalize(subtype)}Type`)58 .mockReturnValueOnce(true);59 jest.spyOn(graphql, "getNamedType").mockReturnValue(entityName);60 const link = printerInstance.toLink(type, entityName);61 expect(link).toMatchFile(path.join(EXPECT_PATH, `toLinkWithList.md`));62 });63 test("returns plain text for unknown entities", () => {64 expect.hasAssertions();65 const type = "any";66 const entityName = "fooBar";67 const link = printerInstance.toLink(type, entityName);68 expect(link).toMatchFile(69 path.join(EXPECT_PATH, `toLinkWithUnknown.md`),70 );71 });72 });73 describe("printSection()", () => {74 test("returns Markdown ### section by default", () => {75 expect.hasAssertions();76 const title = "section title";77 const content = "section content";78 const printSectionItems = jest79 .spyOn(printerInstance, "printSectionItems")80 .mockImplementation((sectionItems) => sectionItems);81 const section = printerInstance.printSection(content, title);82 expect(printSectionItems).toHaveBeenCalledWith(content);83 expect(section).toMatchFile(84 path.join(EXPECT_PATH, `printSection.md`),85 );86 });87 test("returns Markdown custom section level", () => {88 expect.hasAssertions();89 const title = "section title";90 const content = "section content";91 jest92 .spyOn(printerInstance, "printSectionItems")93 .mockImplementation((sectionItems) => sectionItems);94 const section = printerInstance.printSection(content, title, "#");95 expect(section).toMatchFile(96 path.join(EXPECT_PATH, `printSectionCustomLevel.md`),97 );98 });99 test("returns empty string if content is empty", () => {100 expect.hasAssertions();101 const title = "section title";102 const content = "";103 const section = printerInstance.printSection(content, title);104 expect(section).toBe("");105 });106 });107 describe("printSectionItems()", () => {108 test("returns Markdown one line per item", () => {109 expect.hasAssertions();110 const printSectionItem = jest111 .spyOn(printerInstance, "printSectionItem")112 .mockImplementation((sectionItems) => sectionItems);113 const itemList = ["one", "two", "three"];114 const section = printerInstance.printSectionItems(itemList);115 expect(printSectionItem).toHaveBeenCalledTimes(3);116 expect(printSectionItem).toHaveBeenLastCalledWith(117 itemList.pop(),118 "####",119 );120 expect(section).toMatchFile(121 path.join(EXPECT_PATH, `printSectionItems.md`),122 );123 });124 test("returns empty text if not a list", () => {125 expect.hasAssertions();126 const itemList = "list";127 const section = printerInstance.printSectionItems(itemList);128 expect(section).toMatch("");129 });130 });131 describe("printSectionItem()", () => {132 test("returns Markdown #### link section with description", () => {133 expect.hasAssertions();134 const type = { name: "EntityTypeName", description: "Lorem ipsum" };135 jest.spyOn(graphql, "getTypeName").mockReturnValue(type.name);136 jest.spyOn(graphql, "getNamedType").mockReturnValue(type.name);137 jest.spyOn(graphql, "isObjectType").mockReturnValueOnce(true);138 const section = printerInstance.printSectionItem(type);139 expect(section).toMatchFile(140 path.join(EXPECT_PATH, `printSectionItem.md`),141 );142 });143 test("returns Markdown #### link section with sub type", () => {144 expect.hasAssertions();145 const type = {146 name: "EntityTypeName",147 type: { name: "AnObjectType" },148 };149 jest150 .spyOn(graphql, "getTypeName")151 .mockImplementation((paramType) => paramType.name);152 jest153 .spyOn(graphql, "getNamedType")154 .mockImplementation((paramType) => paramType.name);155 jest156 .spyOn(graphql, "isObjectType")157 .mockReturnValueOnce(false)158 .mockReturnValueOnce(true);159 const section = printerInstance.printSectionItem(type);160 expect(section).toMatchFile(161 path.join(EXPECT_PATH, `printSectionItemWithSubType.md`),162 );163 });164 test("returns Markdown #### link section with field parameters", () => {165 expect.hasAssertions();166 const type = {167 name: "EntityTypeName",168 args: [{ name: "ParameterTypeName" }],169 };170 jest171 .spyOn(graphql, "getTypeName")172 .mockImplementation((paramType) => paramType.name);173 jest174 .spyOn(graphql, "getNamedType")175 .mockImplementation((paramType) => paramType.name);176 jest.spyOn(graphql, "isObjectType").mockReturnValueOnce(true);177 jest.spyOn(graphql, "isParametrizedField").mockReturnValueOnce(true);178 const printSectionItems = jest.spyOn(179 printerInstance,180 "printSectionItems",181 );182 const section = printerInstance.printSectionItem(type);183 expect(printSectionItems).toHaveBeenCalledWith(type.args, "- #####");184 expect(section).toMatchFile(185 path.join(EXPECT_PATH, `printSectionWithFieldParameters.md`),186 );187 });188 });189 describe("printCodeEnum()", () => {190 const type = {191 name: "EnumTypeName",192 getValues: () => [{ name: "one" }, { name: "two" }],193 };194 test("returns enum code structure", () => {195 expect.hasAssertions();196 jest.spyOn(graphql, "isEnumType").mockReturnValueOnce(true);197 jest198 .spyOn(graphql, "getTypeName")199 .mockImplementation((paramType) => paramType.name);200 const code = printerInstance.printCodeEnum(type);201 expect(code).toMatchFile(path.join(EXPECT_PATH, `printCodeEnum.md`));202 });203 test("returns empty string if not enum type", () => {204 expect.hasAssertions();205 jest.spyOn(graphql, "isEnumType").mockReturnValueOnce(false);206 const code = printerInstance.printCodeEnum(type);207 expect(code).toBe("");208 });209 });210 describe("printCodeUnion()", () => {211 const type = {212 name: "UnionTypeName",213 getTypes: () => [{ name: "one" }, { name: "two" }],214 };215 test("returns union code structure", () => {216 expect.hasAssertions();217 jest.spyOn(graphql, "isUnionType").mockReturnValueOnce(true);218 jest219 .spyOn(graphql, "getTypeName")220 .mockImplementation((paramType) => paramType.name);221 const code = printerInstance.printCodeUnion(type);222 expect(code).toMatchFile(path.join(EXPECT_PATH, `printCodeUnion.md`));223 });224 test("returns empty string if not union type", () => {225 expect.hasAssertions();226 jest.spyOn(graphql, "isUnionType").mockReturnValueOnce(false);227 const code = printerInstance.printCodeUnion(type);228 expect(code).toBe("");229 });230 });231 describe("printCodeScalar()", () => {232 const type = {233 name: "ScalarTypeName",234 };235 test("returns scalar code structure", () => {236 expect.hasAssertions();237 jest238 .spyOn(graphql, "getTypeName")239 .mockImplementation((paramType) => paramType.name);240 const code = printerInstance.printCodeScalar(type);241 expect(code).toMatchFile(242 path.join(EXPECT_PATH, `printCodeScalar.md`),243 );244 });245 });246 describe("printCodeArguments()", () => {247 test("returns a Markdown one line per formatted argument with default value surrounded by ()", () => {248 expect.hasAssertions();249 const type = {250 name: "OperationName",251 args: [252 {253 name: "ParamWithDefault",254 type: "string",255 default: "defaultValue",256 },257 { name: "ParamNoDefault", type: "any" },258 ],259 };260 jest261 .spyOn(graphql, "getDefaultValue")262 .mockImplementation((paramType) => paramType.default || null);263 const code = printerInstance.printCodeArguments(type);264 expect(code).toMatchFile(265 path.join(EXPECT_PATH, `printCodeArguments.md`),266 );267 });268 test("returns an empty string if args list empty", () => {269 expect.hasAssertions();270 const type = {271 name: "OperationName",272 args: [],273 };274 const code = printerInstance.printCodeArguments(type);275 expect(code).toBe("");276 });277 test("returns an empty string if no args", () => {278 expect.hasAssertions();279 const type = {280 name: "OperationName",281 };282 const code = printerInstance.printCodeArguments(type);283 expect(code).toBe("");284 });285 });286 describe("printCodeField()", () => {287 test("returns a field with its type", () => {288 expect.hasAssertions();289 const type = { name: "FooBar", type: "string" };290 jest291 .spyOn(graphql, "getTypeName")292 .mockReturnValueOnce(type.name)293 .mockReturnValueOnce(type.type);294 jest295 .spyOn(printerInstance, "printCodeArguments")296 .mockReturnValueOnce("");297 const code = printerInstance.printCodeField(type);298 expect(code).toMatchFile(path.join(EXPECT_PATH, "printCodeField.md"));299 });300 test("returns a field with its type and arguments", () => {301 expect.hasAssertions();302 const type = { name: "FooBar", type: "string" };303 jest304 .spyOn(graphql, "getTypeName")305 .mockReturnValueOnce(type.name)306 .mockReturnValueOnce(type.type);307 jest308 .spyOn(printerInstance, "printCodeArguments")309 .mockReturnValueOnce("(\narg: boolean\n)");310 const code = printerInstance.printCodeField(type);311 expect(code).toMatchFile(312 path.join(EXPECT_PATH, "printCodeFieldWithArguments.md"),313 );314 });315 });316 describe("printCodeDirective()", () => {317 test("returns a directive", () => {318 expect.hasAssertions();319 const type = { name: "FooBar", type: "string" };320 jest.spyOn(graphql, "getTypeName").mockReturnValueOnce(type.name);321 jest322 .spyOn(printerInstance, "printCodeArguments")323 .mockReturnValueOnce("");324 const code = printerInstance.printCodeDirective(type);325 expect(code).toMatchFile(326 path.join(EXPECT_PATH, "printCodeDirective.md"),327 );328 });329 test("returns a directive with its arguments", () => {330 expect.hasAssertions();331 const type = { name: "FooBar", type: "string" };332 jest.spyOn(graphql, "getTypeName").mockReturnValueOnce(type.name);333 jest334 .spyOn(printerInstance, "printCodeArguments")335 .mockReturnValueOnce("(\narg: boolean\n)");336 const code = printerInstance.printCodeDirective(type);337 expect(code).toMatchFile(338 path.join(EXPECT_PATH, "printCodeDirectiveWithArguments.md"),339 );340 });341 });342 describe("printCodeType()", () => {343 test("returns an interface with its fields", () => {344 expect.hasAssertions();345 const type = { name: "TestInterfaceName", fields: ["one", "two"] };346 jest.spyOn(graphql, "isInterfaceType").mockReturnValueOnce(true);347 jest.spyOn(graphql, "getTypeName").mockReturnValueOnce()(type.name);348 jest.spyOn(graphql, "getFields").mockReturnValueOnce(type.fields);349 jest350 .spyOn(printerInstance, "printCodeField")351 .mockImplementation((name) => `${name}\n`);352 const code = printerInstance.printCodeType(type);353 expect(code).toMatchFile(354 path.join(EXPECT_PATH, "printCodeTypeWithInterface.md"),355 );356 });357 test("returns an object with its fields and interfaces", () => {358 expect.hasAssertions();359 const type = {360 name: "TestName",361 fields: ["one", "two"],362 getInterfaces: () => [{ name: "TestInterfaceName" }],363 };364 jest.spyOn(graphql, "isInterfaceType").mockReturnValueOnce(false);365 jest366 .spyOn(graphql, "getTypeName")367 .mockImplementation((entityType) => entityType.name);368 jest.spyOn(graphql, "getFields").mockReturnValueOnce(type.fields);369 jest370 .spyOn(printerInstance, "printCodeField")371 .mockImplementation((codeField) => `${codeField}\n`);372 const code = printerInstance.printCodeType(type);373 expect(code).toMatchFile(374 path.join(EXPECT_PATH, "printCodeTypeWithObject.md"),375 );376 });377 });378 describe("printHeader()", () => {379 test("returns a Docusaurus document header", () => {380 expect.hasAssertions();381 const header = printerInstance.printHeader(382 "an-object-type-name",383 "An Object Type Name",384 );385 expect(header).toMatchFile(path.join(EXPECT_PATH, "printHeader.md"));386 });387 });388 describe("printDescription()", () => {389 test("returns the type description text", () => {390 expect.hasAssertions();391 const type = { description: "Lorem ipsum" };392 const description = printerInstance.printDescription(type);393 expect(description).toMatchFile(394 path.join(EXPECT_PATH, "printDescription.md"),395 );396 });397 test("returns the default text if no description", () => {398 expect.hasAssertions();399 const type = {};400 const description = printerInstance.printDescription(type);401 expect(description).toMatchFile(402 path.join(EXPECT_PATH, "printDescriptionWithDefault.md"),403 );404 });405 test("return DEPRECATED tag if deprecated", () => {406 const type = {407 description: "Lorem ipsum",408 isDeprecated: true,409 deprecationReason: "Foobar",410 };411 const description = printerInstance.printDescription(type);412 expect(description).toMatchFile(413 path.join(EXPECT_PATH, "printDescriptionWithDeprecated.md"),414 );415 });416 });417 describe("printCode()", () => {418 test.each(graphQLEntityType)(419 "returns a Markdown graphql codeblock with type %s",420 (type) => {421 expect.hasAssertions();422 const entityName = `Test${capitalize(type)}`;423 jest424 .spyOn(graphql, `is${capitalize(type)}Type`)425 .mockReturnValueOnce(true);426 let printCode;427 if (["interface", "object", "input"].includes(type)) {428 printCode = jest429 .spyOn(printerInstance, "printCodeType")430 .mockReturnValueOnce(entityName);431 } else {432 printCode = jest433 .spyOn(printerInstance, `printCode${capitalize(type)}`)434 .mockReturnValueOnce(entityName);435 }436 const code = printerInstance.printCode(entityName);437 expect(printCode).toHaveBeenCalledWith(entityName);438 expect(code).toMatchFile(439 path.join(EXPECT_PATH, `printCodeWith${capitalize(type)}.md`),440 );441 },442 );443 test("returns a Markdown graphql codeblock with type query", () => {444 expect.hasAssertions();445 const entityName = "TestQuery";446 jest.spyOn(graphql, "isOperation").mockReturnValueOnce(true);447 const printCode = jest448 .spyOn(printerInstance, "printCodeField")449 .mockReturnValueOnce(entityName);450 const code = printerInstance.printCode(entityName);451 expect(printCode).toHaveBeenCalledWith(entityName);452 expect(code).toMatchFile(453 path.join(EXPECT_PATH, "printCodeWithQuery.md"),454 );455 });456 test("returns a Markdown codeblock with non supported message for unsupported type", () => {457 expect.hasAssertions();458 const entityName = "TestFooBarType";459 jest.spyOn(graphql, "getTypeName").mockReturnValueOnce(entityName);460 const code = printerInstance.printCode(entityName);461 expect(code).toMatchFile(462 path.join(EXPECT_PATH, "printCodeWithUnsupported.md"),463 );464 });465 });466 describe("printType()", () => {467 test.each(graphQLEntityType)(468 "returns a Markdown formatted Docusaurus content for type %s",469 (type) => {470 expect.hasAssertions();471 const entityType = {472 name: type,473 getValues: () => {},474 getTypes: () => {},475 };476 jest477 .spyOn(graphql, `is${capitalize(type)}Type`)478 .mockReturnValueOnce(true);479 jest480 .spyOn(printerInstance, "printHeader")481 .mockImplementation((header) => `header-${header}`);482 jest483 .spyOn(printerInstance, "printDescription")484 .mockImplementation(485 (paramType) => `Test ${capitalize(paramType.name)}`,486 );487 jest488 .spyOn(printerInstance, "printCode")489 .mockImplementation(490 (paramType) => `\`\`\`${paramType.name}\`\`\``,491 );492 jest493 .spyOn(printerInstance, "printSection")494 .mockImplementation((_, section) => section);495 const printedType = printerInstance.printType(496 entityType.name,497 entityType,498 );499 expect(printedType).toMatchFile(500 path.join(EXPECT_PATH, `printTypeWith${capitalize(type)}.md`),501 );502 },503 );504 test.each(["object", "input"])(505 "returns a Markdown formatted Docusaurus content for %s implementing interface",506 (type) => {507 expect.hasAssertions();508 const entityType = {509 name: type,510 getValues: () => ({}),511 getTypes: () => ({}),512 getInterfaces: () => ({}),513 };514 jest515 .spyOn(graphql, `is${capitalize(type)}Type`)516 .mockReturnValueOnce(true);517 jest518 .spyOn(printerInstance, "printHeader")519 .mockImplementation((name) => `header-${name}\n\n`);520 jest521 .spyOn(printerInstance, "printDescription")522 .mockImplementation(523 (type) => `Test ${capitalize(type.name)}\n\n`,524 );525 jest526 .spyOn(printerInstance, "printCode")527 .mockImplementation((type) => `\`\`\`${type.name}\`\`\`\n\n`);528 jest529 .spyOn(printerInstance, "printSection")530 .mockImplementation((_, section) => `${section}\n\n`);531 const printedType = printerInstance.printType(532 entityType.name,533 entityType,534 );535 expect(printedType).toMatchFile(536 path.join(537 EXPECT_PATH,538 `printTypeWith${capitalize(type)}Interface.md`,539 ),540 );541 },542 );543 test("returns a Markdown formatted Docusaurus content for query", () => {544 expect.hasAssertions();545 const entityType = {546 name: "query",547 };548 jest.spyOn(graphql, "isOperation").mockReturnValue(true);549 jest.spyOn(graphql, "getTypeName").mockReturnValue(entityType.name);550 jest551 .spyOn(printerInstance, "printHeader")552 .mockImplementation((name) => `header-${name}\n\n`);553 jest554 .spyOn(printerInstance, "printDescription")555 .mockImplementation(556 (paramType) => `Test ${capitalize(paramType.name)}\n\n`,557 );558 jest559 .spyOn(printerInstance, "printCode")560 .mockImplementation(561 (paramType) => `\`\`\`${paramType.name}\`\`\`\n\n`,562 );563 jest564 .spyOn(printerInstance, "printSection")565 .mockImplementation((_, section) => `${section}\n\n`);566 const printedType = printerInstance.printType(567 entityType.name,568 entityType,569 );570 expect(printedType).toMatchFile(571 path.join(EXPECT_PATH, `printTypeWithQuery.md`),572 );573 });574 test("returns an empty string if no type", () => {575 expect.hasAssertions();576 const printedType = printerInstance.printType("any", null);577 expect(printedType).toBe("");578 });579 test("prints a specification section if scalar as directive @specifiedBy", () => {580 expect.hasAssertions();581 const scalarType = {582 name: "Lorem Scalar",583 description: "Lorem Ipsum",584 specifiedByUrl: "http://lorem.ipsum",585 toString: () => "Lorem Scalar To String",586 };587 jest.spyOn(graphql, "isScalarType").mockReturnValue(true);588 const printedType = printerInstance.printType("scalar", scalarType);589 expect(printedType).toMatchFile(590 path.join(EXPECT_PATH, `printTypeWithScalarWithSpecifiedBy.md`),591 );592 });593 });594 });...

Full Screen

Full Screen

module-servers-test.js

Source:module-servers-test.js Github

copy

Full Screen

...22describe('module-servers', () => {23 describe('epics', () => {24 describe('gameStarts', () => {25 it('should initialize the server on startup only once', () => {26 expect.hasAssertions();27 const values = {28 a: { type: 'GAME_STARTED' },29 b: { type: 'SERVERS_INITIALIZED', data: getEnv() },30 c: { type: 'UNKNOWN_ACTION' },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', () => {204 const stateAfterInitialization = {205 servers: {206 'http://us.warx.io': {207 address: 'http://us.warx.io',208 location: 'us',209 name: 'warx-us',210 numPlayers: 0,211 maxPlayers: 6,212 numBots: 2,213 }214 },215 bots: {216 '1': {},217 '2': {},218 },219 currentServer: 'http://us.warx.io',220 isLoadingServers: true,221 isHub: false,222 isRegistered: false,223 players: {},224 lastHubCheck: 0,225 isConnectedToHubNetwork: true,226 };227 it('should add itself to the list of servers on SERVERS_INITIALIZED', () => {228 expect.hasAssertions();229 const resultState = reducer(initialStateWithPlayers, {230 type: 'SERVERS_INITIALIZED',231 origin: 'server',232 data: {233 address: 'http://us.warx.io',234 location: 'us',235 name: 'warx-us',236 hub: 'http://www.warx.io',237 numBots: 2,238 maxPlayers: 6,239 numPlayers: 0,240 isTrusted: true,241 }242 });243 expect(resultState).toEqual(stateAfterInitialization);244 });245 describe('should save the time after a checkup from the hub', () => {246 expect.hasAssertions();247 const now = Number(Date.now());248 const resultState = reducer(249 stateAfterInitialization,250 createServerCheckReceived({251 time: now,252 })253 );254 expect(resultState.lastHubCheck).toEqual(now);255 });256 it('should save the servers after SERVERS_REGISTER_RESPONSE', () => {257 expect.hasAssertions();258 const resultState = reducer(stateAfterInitialization, {259 type: 'SERVERS_REGISTER_RESPONSE',260 origin: 'server',261 data: {262 servers: {263 'http://us2.warx.io': {264 address: 'http://us2.warx.io',265 location: 'us',266 name: 'warx-us2',267 numPlayers: 2,268 maxPlayers: 6,269 numBots: 2,270 },271 'http://www.warx.io': {272 address: 'http://www.warx.io',273 location: 'eu',274 name: 'warx',275 numPlayers: 10,276 maxPlayers: 10,277 numBots: 2,278 },279 }280 }281 });282 expect(resultState).toEqual({283 servers: {284 'http://us.warx.io': {285 address: 'http://us.warx.io',286 location: 'us',287 name: 'warx-us',288 maxPlayers: 6,289 numBots: 2,290 numPlayers: 0,291 },292 'http://us2.warx.io': {293 address: 'http://us2.warx.io',294 location: 'us',295 name: 'warx-us2',296 numPlayers: 2,297 maxPlayers: 6,298 numBots: 2,299 },300 'http://www.warx.io': {301 address: 'http://www.warx.io',302 location: 'eu',303 name: 'warx',304 numPlayers: 10,305 maxPlayers: 10,306 numBots: 2,307 },308 },309 currentServer: 'http://us.warx.io',310 isLoadingServers: false,311 isHub: false,312 isRegistered: true,313 players: {},314 lastHubCheck: 0,315 isConnectedToHubNetwork: true,316 bots: {317 '1': {},318 '2': {},319 },320 });321 });322 });323 describe('hub', () => {324 const resultState = reducer(initialStateWithPlayers, {325 type: 'SERVERS_INITIALIZED',326 origin: 'server',327 data: {328 address: 'http://www.warx.io',329 location: 'eu',330 name: 'warx-eu',331 hub: 'http://www.warx.io',332 numBots: 2,333 numPlayers: 5,334 maxPlayers: 6,335 isTrusted: true,336 }337 });338 it('should add itself to the list of servers on SERVERS_INITIALIZED', () => {339 expect.hasAssertions();340 expect(resultState).toEqual({341 servers: {342 'http://www.warx.io': {343 address: 'http://www.warx.io',344 location: 'eu',345 name: 'warx-eu',346 numPlayers: 5,347 numBots: 2,348 maxPlayers: 6,349 }350 },351 currentServer: 'http://www.warx.io',352 isLoadingServers: false,353 isHub: true,354 isRegistered: true,355 players: {},356 lastHubCheck: 0,357 isConnectedToHubNetwork: true,358 bots: {359 '1': {},360 '2': {},361 },362 });363 });364 const now1 = Number(Date.now());365 const checkResult1 = reducer(resultState, {366 type: 'SERVERS_HUB_CHECK_SUCCESS',367 origin: 'server',368 data: {369 lastUpdated: now1,370 address: 'http://us.warx.io',371 location: 'us',372 name: 'warx-us',373 numPlayers: 5,374 maxPlayers: 4,375 numBots: 1,376 }377 });378 it('should add the server on SERVERS_HUB_CHECK_SUCCESS', () => {379 expect.hasAssertions();380 expect(checkResult1).toEqual({381 servers: {382 'http://www.warx.io': {383 address: 'http://www.warx.io',384 location: 'eu',385 name: 'warx-eu',386 numPlayers: 5,387 numBots: 2,388 maxPlayers: 6,389 },390 'http://us.warx.io': {391 address: 'http://us.warx.io',392 location: 'us',393 name: 'warx-us',394 numPlayers: 5,395 maxPlayers: 4,396 numBots: 1,397 lastUpdated: now1,398 },399 },400 currentServer: 'http://www.warx.io',401 isLoadingServers: false,402 isHub: true,403 isRegistered: true,404 players: {},405 lastHubCheck: 0,406 isConnectedToHubNetwork: true,407 bots: { '1': {}, '2': {}}408 });409 });410 const now2 = Number(Date.now());411 const checkResult2 = reducer(checkResult1, {412 type: 'SERVERS_HUB_CHECK_SUCCESS',413 origin: 'server',414 data: {415 lastUpdated: now2,416 address: 'http://us.warx.io',417 location: 'us',418 name: 'warx-us',419 numPlayers: 8,420 numBots: 1,421 maxPlayers: 8,422 }423 });424 it('should update an existing server on SERVERS_HUB_CHECK_SUCCESS', () => {425 expect.hasAssertions();426 expect(checkResult2).toEqual({427 servers: {428 'http://www.warx.io': {429 address: 'http://www.warx.io',430 location: 'eu',431 name: 'warx-eu',432 numPlayers: 5,433 numBots: 2,434 maxPlayers: 6,435 },436 'http://us.warx.io': {437 address: 'http://us.warx.io',438 location: 'us',439 name: 'warx-us',440 numPlayers: 8,441 numBots: 1,442 maxPlayers: 8,443 lastUpdated: now2,444 },445 },446 currentServer: 'http://www.warx.io',447 isLoadingServers: false,448 isHub: true,449 isRegistered: true,450 players: {},451 lastHubCheck: 0,452 isConnectedToHubNetwork: true,453 bots: { '1': {}, '2': {}}454 });455 });456 const checkResult3 = reducer(checkResult2, {457 type: 'SERVERS_HUB_CHECK_ERROR',458 origin: 'server',459 data: {460 address: 'http://us.warx.io',461 }462 });463 it('should remove the server on SERVERS_HUB_CHECK_ERROR', () => {464 expect.hasAssertions();465 expect(checkResult3).toEqual({466 servers: {467 'http://www.warx.io': {468 address: 'http://www.warx.io',469 location: 'eu',470 name: 'warx-eu',471 numPlayers: 5,472 numBots: 2,473 maxPlayers: 6,474 },475 },476 currentServer: 'http://www.warx.io',477 isLoadingServers: false,478 isHub: true,...

Full Screen

Full Screen

graphql.test.js

Source:graphql.test.js Github

copy

Full Screen

...69 });70 });71 describe("getDefaultValue()", () => {72 test("returns default value as an integer when defined", () => {73 expect.hasAssertions();74 const argument = {75 name: "foobar",76 description: undefined,77 type: GraphQLInt,78 defaultValue: 5,79 extensions: undefined,80 };81 expect(getDefaultValue(argument)).toBe(5);82 });83 test("returns default value as a float when defined", () => {84 expect.hasAssertions();85 const argument = {86 name: "foobar",87 description: undefined,88 type: GraphQLFloat,89 defaultValue: 5.3,90 extensions: undefined,91 };92 expect(getDefaultValue(argument)).toBe(5.3);93 });94 test("returns undefined for type GraphQLInt if not default value defined", () => {95 expect.hasAssertions();96 const argument = {97 name: "foobar",98 description: undefined,99 type: GraphQLInt,100 defaultValue: undefined,101 extensions: undefined,102 };103 expect(getDefaultValue(argument)).toBeUndefined();104 });105 test("returns undefined for type GraphQLID if not default value defined", () => {106 expect.hasAssertions();107 const argument = {108 name: "foobar",109 description: undefined,110 type: GraphQLID,111 defaultValue: undefined,112 extensions: undefined,113 };114 expect(getDefaultValue(argument)).toBeUndefined();115 });116 test("returns undefined for type GraphQLFloat if not default value defined", () => {117 expect.hasAssertions();118 const argument = {119 name: "foobar",120 description: undefined,121 type: GraphQLFloat,122 defaultValue: undefined,123 extensions: undefined,124 };125 expect(getDefaultValue(argument)).toBeUndefined();126 });127 test("returns undefined for type GraphQLString if not default value defined", () => {128 expect.hasAssertions();129 const argument = {130 name: "foobar",131 description: undefined,132 type: GraphQLString,133 defaultValue: undefined,134 extensions: undefined,135 };136 expect(getDefaultValue(argument)).toBeUndefined();137 });138 test("returns undefined for type GraphQLList without default value", () => {139 expect.hasAssertions();140 const argument = {141 name: "id",142 description: undefined,143 type: new GraphQLList(GraphQLID),144 defaultValue: undefined,145 extensions: undefined,146 };147 expect(getDefaultValue(argument)).toBeUndefined();148 });149 test("returns array default value as string for type GraphQLList(GraphQLID)", () => {150 expect.hasAssertions();151 const argument = {152 name: "id",153 description: undefined,154 type: new GraphQLList(GraphQLID),155 defaultValue: ["0", "1"],156 extensions: undefined,157 };158 expect(getDefaultValue(argument)).toBe('["0", "1"]');159 });160 test("returns array default value as string for type GraphQLList(GraphQLInt)", () => {161 expect.hasAssertions();162 const argument = {163 name: "foobar",164 description: undefined,165 type: new GraphQLList(GraphQLInt),166 defaultValue: [0, 1],167 extensions: undefined,168 };169 expect(getDefaultValue(argument)).toBe("[0, 1]");170 });171 });172 describe("getFilteredTypeMap()", () => {173 test("returns a filtered map of schema types", () => {174 expect.hasAssertions();175 const schemaTypeMap = getFilteredTypeMap(schema.getTypeMap());176 expect(JSON.stringify(schemaTypeMap, null, 2)).toMatchFile(177 path.join(EXPECT_PATH, `getFilteredTypeMap.json`),178 );179 });180 });181 describe("getIntrospectionFieldsList()", () => {182 test("returns list of queries", () => {183 expect.hasAssertions();184 const list = getIntrospectionFieldsList(schema.getQueryType());185 expect(JSON.stringify(list, null, 2)).toMatchFile(186 path.join(EXPECT_PATH, `getIntrospectionFieldsListQueries.json`),187 );188 });189 test("returns list of mutations", () => {190 expect.hasAssertions();191 const list = getIntrospectionFieldsList(schema.getMutationType());192 expect(JSON.stringify(list, null, 2)).toMatchFile(193 path.join(EXPECT_PATH, `getIntrospectionFieldsListMutations.json`),194 );195 });196 test("returns list of subscriptions", () => {197 expect.hasAssertions();198 const list = getIntrospectionFieldsList(schema.getSubscriptionType());199 expect(JSON.stringify(list, null, 2)).toMatchFile(200 path.join(201 EXPECT_PATH,202 `getIntrospectionFieldsListSubscriptions.json`,203 ),204 );205 });206 test("returns undefined if null", () => {207 expect.hasAssertions();208 const list = getIntrospectionFieldsList(null);209 expect(list).toBeUndefined();210 });211 });212 describe("getFields()", () => {213 test("returns list of type fields", () => {214 expect.hasAssertions();215 const fields = getFields(schema.getMutationType());216 expect(JSON.stringify(fields, null, 2)).toMatchFile(217 path.join(EXPECT_PATH, `getFields.json`),218 );219 });220 });221 describe("getTypeName()", () => {222 test("returns type name for object", () => {223 expect.hasAssertions();224 const name = getTypeName(schema.getType("Tweet"));225 expect(name).toBe("Tweet");226 });227 test("returns type name for interface", () => {228 expect.hasAssertions();229 const name = getTypeName(schema.getType("Node"));230 expect(name).toBe("Node");231 });232 test("returns type name for scalar", () => {233 expect.hasAssertions();234 const name = getTypeName(schema.getType("ID"));235 expect(name).toBe("ID");236 });237 test("returns default name for unknown", () => {238 expect.hasAssertions();239 const name = getTypeName({ toString: undefined }, "FooBar");240 expect(name).toBe("FooBar");241 });242 });243 describe("getTypeFromTypeMap()", () => {244 test("returns a filter map filtered by GraphQLObjectType", () => {245 expect.hasAssertions();246 const map = getTypeFromTypeMap(schema.getTypeMap(), GraphQLObjectType);247 expect(JSON.stringify(map, null, 2)).toMatchFile(248 path.join(EXPECT_PATH, `getTypeFromTypeMapGraphQLObjectType.json`),249 );250 });251 test("returns a filter map filtered by GraphQLUnionType", () => {252 expect.hasAssertions();253 const map = getTypeFromTypeMap(schema.getTypeMap(), GraphQLUnionType);254 expect(JSON.stringify(map, null, 2)).toMatchFile(255 path.join(EXPECT_PATH, `getTypeFromTypeMapGraphQLUnionType.json`),256 );257 });258 test("returns a filter map filtered by GraphQLInterfaceType", () => {259 expect.hasAssertions();260 const map = getTypeFromTypeMap(261 schema.getTypeMap(),262 GraphQLInterfaceType,263 );264 expect(JSON.stringify(map, null, 2)).toMatchFile(265 path.join(EXPECT_PATH, `getTypeFromTypeMapGraphQLInterfaceType.json`),266 );267 });268 test("returns a filter map filtered by GraphQLEnumType", () => {269 expect.hasAssertions();270 const map = getTypeFromTypeMap(schema.getTypeMap(), GraphQLEnumType);271 expect(JSON.stringify(map, null, 2)).toMatchFile(272 path.join(EXPECT_PATH, `getTypeFromTypeMapGraphQLEnumType.json`),273 );274 });275 test("returns a filter map filtered by GraphQLInputObjectType", () => {276 expect.hasAssertions();277 const map = getTypeFromTypeMap(278 schema.getTypeMap(),279 GraphQLInputObjectType,280 );281 expect(JSON.stringify(map, null, 2)).toMatchFile(282 path.join(283 EXPECT_PATH,284 `getTypeFromTypeMapGraphQLInputObjectType.json`,285 ),286 );287 });288 test("returns a filter map filtered by GraphQLScalarType", () => {289 expect.hasAssertions();290 const map = getTypeFromTypeMap(schema.getTypeMap(), GraphQLScalarType);291 expect(JSON.stringify(map, null, 2)).toMatchFile(292 path.join(EXPECT_PATH, `getTypeFromTypeMapGraphQLScalarType.json`),293 );294 });295 });296 describe("getSchemaMap()", () => {297 test("returns schema types map", () => {298 expect.hasAssertions();299 const schemaTypeMap = getSchemaMap(schema);300 expect(JSON.stringify(schemaTypeMap, null, 2)).toMatchFile(301 path.join(EXPECT_PATH, `getSchemaMap.json`),302 );303 });304 });305 describe("isParametrizedField()", () => {306 test("returns true if type is parametrized", () => {307 expect.hasAssertions();308 const mutations = getIntrospectionFieldsList(schema.getMutationType());309 const res = isParametrizedField(mutations["createTweet"]);310 expect(res).toBeTruthy();311 });312 test("returns false if type is not parametrized", () => {313 expect.hasAssertions();314 const queries = getIntrospectionFieldsList(schema.getQueryType());315 const res = isParametrizedField(queries["TweetsMeta"]);316 expect(res).toBeFalsy();317 });318 });319 describe("isOperation()", () => {320 test("returns true if type is mutation", () => {321 expect.hasAssertions();322 const mutations = getIntrospectionFieldsList(schema.getMutationType());323 const res = isOperation(mutations["createTweet"]);324 expect(res).toBeTruthy();325 });326 test("returns true if type is query", () => {327 expect.hasAssertions();328 const queries = getIntrospectionFieldsList(schema.getQueryType());329 const res = isOperation(queries["Tweets"]);330 expect(res).toBeTruthy();331 });332 test("returns true if type is subscription", () => {333 expect.hasAssertions();334 const subscriptions = getIntrospectionFieldsList(335 schema.getSubscriptionType(),336 );337 const res = isOperation(subscriptions["Notifications"]);338 expect(res).toBeTruthy();339 });340 test("returns false if type is not an operation", () => {341 expect.hasAssertions();342 const objects = getTypeFromTypeMap(343 schema.getTypeMap(),344 GraphQLObjectType,345 );346 const res = isOperation(objects["Tweet"]);347 expect(res).toBeFalsy();348 });349 });350 });...

Full Screen

Full Screen

movies.test.js

Source:movies.test.js Github

copy

Full Screen

...122 });123 });124 });125 it('Не заполнено nameRU', async () => {126 expect.hasAssertions();127 return createMovie(128 { ...movieData, nameRU: '', movieId: movieIdRand() },129 ).then(testBadRequestCheck);130 });131 it('Не корректное movieId', async () => {132 expect.hasAssertions();133 return createMovie(134 { ...movieData, movieId: movieIdInvalid },135 ).then(testBadRequestCheck);136 });137 it('Не корректное duration', async () => {138 expect.hasAssertions();139 return createMovie(140 { ...movieData, duration: durationInvalid },141 ).then(testBadRequestCheck);142 });143 describe('Тестируем image', () => {144 it('Слишком короткая длина', async () => {145 expect.hasAssertions();146 return createMovie(147 { ...movieData, image: imageShort },148 ).then(testBadRequestCheck);149 });150 it('Слишком длинная длина', async () => {151 expect.hasAssertions();152 return createMovie(153 { ...movieData, image: imageLong },154 ).then(testBadRequestCheck);155 });156 it('Не корректной формат изображений', async () => {157 expect.hasAssertions();158 return createMovie(159 { ...movieData, image: imageInvalid },160 ).then(testBadRequestCheck);161 });162 });163 describe('Тестируем trailer', () => {164 it('Слишком короткая длина', async () => {165 expect.hasAssertions();166 return createMovie(167 { ...movieData, image: imageShort },168 ).then(testBadRequestCheck);169 });170 it('Слишком длинная длина', async () => {171 expect.hasAssertions();172 return createMovie(173 { ...movieData, image: imageLong },174 ).then(testBadRequestCheck);175 });176 it('Не корректной формат изображений', async () => {177 expect.hasAssertions();178 return createMovie(179 { ...movieData, image: imageInvalid },180 ).then(testBadRequestCheck);181 });182 });183 describe('Тестируем thumbnail', () => {184 it('Слишком короткая длина', async () => {185 expect.hasAssertions();186 return createMovie(187 { ...movieData, image: imageShort },188 ).then(testBadRequestCheck);189 });190 it('Слишком длинная длина', async () => {191 expect.hasAssertions();192 return createMovie(193 { ...movieData, image: imageLong },194 ).then(testBadRequestCheck);195 });196 it('Не корректной формат изображений', async () => {197 expect.hasAssertions();198 return createMovie(199 { ...movieData, image: imageInvalid },200 ).then(testBadRequestCheck);201 });202 });203 describe('Тестируем удаление фильма', () => {204 it('DELETE "/users/me" (данные верны) должен возвращать корректные данные в json-формате и корректный статус', async () => {205 const { body: { _id } } = await createMovie(206 { ...movieData, movieId: movieIdRand() },207 );208 return agent209 .delete(`/movies/${_id}`)210 .then(({ status, headers, body }) => {211 expect(status).toBe(OK);212 expect(headers['content-type']).toMatch('application/json');213 expect(body).toMatchObject({214 _id,215 });216 });217 });218 it('DELETE "/users/me" (не существующий id)', async () => {219 expect.hasAssertions();220 await createMovie({ ...movieData, movieId: movieIdRand() });221 return agent222 .delete(`/movies/${movieNot._id}`)223 .then(testNotFoundRequestCheck);224 });225 it('DELETE "/users/me" (фильм другого пользователя)', async () => {226 expect.hasAssertions();227 const { body: { _id } } = await createMovie(228 { ...movieData, movieId: movieIdRand() },229 );230 await logout();231 const emailNew = emailRand();232 const passwordNew = passwordRand();233 await signup({234 email: emailNew,235 password: passwordNew,236 name: nameRand(),237 });238 await signin({239 email: emailNew,240 password: passwordNew,...

Full Screen

Full Screen

functions.test.js

Source:functions.test.js Github

copy

Full Screen

1const path = require("path");2const parser = require("../src/functions");3describe("functions", () => {4 it("fails on invalid file", async () => {5 expect.hasAssertions();6 const filename = path.join(__dirname, "unknown.xml");7 await expect(parser.readFile(filename)).rejects.toThrow(8 "no such file or directory"9 );10 });11 it.skip("parses XML to JS", async () => {12 expect.hasAssertions();13 const filename = path.join(__dirname, "/clover.xml");14 const coverage = await parser.readFile(filename);15 expect(coverage).toHaveProperty("coverage");16 expect(coverage.coverage).toHaveProperty("project");17 expect(coverage.coverage.project).toHaveProperty("0");18 expect(coverage.coverage.project[0]).toHaveProperty("metrics");19 expect(coverage.coverage.project[0].metrics).toHaveProperty("0");20 const metric = await parser.readMetric(coverage);21 ["statements", "lines", "methods", "branches"].forEach((type) => {22 expect(metric).toHaveProperty(type);23 expect(metric[type]).toHaveProperty("total");24 expect(metric[type]).toHaveProperty("covered");25 expect(metric[type]).toHaveProperty("rate");26 });27 expect(metric.lines.rate).toStrictEqual(70.59); // 24 / 3428 expect(metric.statements.rate).toStrictEqual(68.18); // 45 / 6629 expect(metric.methods.rate).toStrictEqual(83.33); // 10 / 1230 expect(metric.branches.rate).toStrictEqual(55); // 11 / 2031 expect(metric).toHaveProperty("level");32 expect(metric.level).toStrictEqual("yellow"); // 79.59 < 9033 });34 it("calculates level", async () => {35 expect.hasAssertions();36 [37 [49, 50, 90, "red"],38 [89, 50, 90, "yellow"],39 [90, 50, 90, "green"],40 ].forEach(([linesRate, thresholdAlert, thresholdWarning, level]) => {41 const metric = { lines: { rate: linesRate } };42 const options = { thresholdAlert, thresholdWarning };43 expect(parser.calculateLevel(metric, options)).toStrictEqual(level);44 });45 });46 it("generates status", async () => {47 expect.hasAssertions();48 const targetUrl = "https://example.com";49 const statusContext = "coverage";50 const rate = 50;51 expect(52 parser.generateStatus({53 targetUrl,54 statusContext,55 metric: { lines: { rate }, level: "red" },56 })57 ).toStrictEqual({58 state: "failure",59 description: `Error: Too low coverage - ${rate}%`,60 target_url: targetUrl,61 context: statusContext,62 });63 expect(64 parser.generateStatus({65 targetUrl,66 statusContext,67 metric: { lines: { rate }, level: "yellow" },68 })69 ).toStrictEqual({70 state: "success",71 description: `Warning: low coverage - ${rate}%`,72 target_url: targetUrl,73 context: statusContext,74 });75 expect(76 parser.generateStatus({77 targetUrl,78 statusContext,79 metric: { lines: { rate }, level: "green" },80 })81 ).toStrictEqual({82 state: "success",83 description: `Success: Coverage - ${rate}%`,84 target_url: targetUrl,85 context: statusContext,86 });87 });88 it("generates badge URL", async () => {89 expect.hasAssertions();90 const metric = {91 lines: { rate: 9.4 },92 level: "green",93 };94 expect(parser.generateBadgeUrl(metric)).toStrictEqual(95 "https://img.shields.io/static/v1?label=coverage&message=9%&color=green"96 );97 });98 it("generates emoji", async () => {99 expect.hasAssertions();100 expect(parser.generateEmoji({ lines: { rate: 100 } })).toStrictEqual(" 🎉");101 expect(parser.generateEmoji({ lines: { rate: 99.99 } })).toStrictEqual("");102 });103 it("generates header", async () => {104 expect.hasAssertions();105 expect(106 parser.generateCommentHeader({ commentContext: "foobar" })107 ).toStrictEqual(`<!-- coverage-monitor-action: foobar -->`);108 });109 it("generates table", async () => {110 expect.hasAssertions();111 const metric = {112 statements: {113 total: 10,114 covered: 1,115 rate: 10,116 },117 lines: {118 total: 10,119 covered: 2,120 rate: 20,121 },122 methods: {123 total: 10,124 covered: 3,125 rate: 30,126 },127 branches: {128 total: 10,129 covered: 4,130 rate: 40,131 },132 level: "yellow",133 };134 const expectedString = `<!-- coverage-monitor-action: Coverage Report -->135## Coverage Report136| Totals | ![Coverage](https://img.shields.io/static/v1?label=coverage&message=20%&color=yellow) |137| :-- | --: |138| Statements: | 20% ( 2 / 10 ) |139| Methods: | 30% ( 3 / 10 ) |140`;141 expect(142 parser.generateTable({ metric, commentContext: "Coverage Report" })143 ).toStrictEqual(expectedString);144 });145 function createConfigReader(inputs) {146 return {147 getInput(name) {148 return inputs[149 name150 .split("_")151 .reduce(152 (carry, item) =>153 carry === null154 ? item155 : `${carry}${item[0].toUpperCase() + item.slice(1)}`,156 null157 )158 ];159 },160 };161 }162 it("loads config", async () => {163 expect.hasAssertions();164 const inputs = {165 comment: true,166 check: false,167 githubToken: "***",168 cloverFile: "clover.xml",169 thresholdAlert: 10,170 thresholdWarning: 20,171 statusContext: "Coverage",172 commentContext: "Coverage Report",173 commentMode: "replace",174 };175 const reader = createConfigReader(inputs);176 const config = parser.loadConfig(reader);177 expect(config).toStrictEqual(inputs);178 });179 it("uses defaults on loading config", async () => {180 expect.hasAssertions();181 const inputs = {182 githubToken: "***",183 cloverFile: "clover.xml",184 };185 const expected = {186 comment: false,187 check: false,188 githubToken: "***",189 cloverFile: "clover.xml",190 thresholdAlert: 90,191 thresholdWarning: 50,192 statusContext: "Coverage Report",193 commentContext: "Coverage Report",194 commentMode: "replace",195 };196 const reader = createConfigReader(inputs);197 const config = parser.loadConfig(reader);198 expect(config).toStrictEqual(expected);199 });200 it("coerces config values", async () => {201 expect.hasAssertions();202 const inputs = {203 comment: "true",204 check: "false",205 githubToken: "***",206 cloverFile: "clover.xml",207 thresholdAlert: "10",208 thresholdWarning: "20",209 statusContext: "Coverage",210 commentContext: "Coverage Report",211 commentMode: "replace",212 };213 const expected = {214 comment: true,215 check: false,216 githubToken: "***",217 cloverFile: "clover.xml",218 thresholdAlert: 10,219 thresholdWarning: 20,220 statusContext: "Coverage",221 commentContext: "Coverage Report",222 commentMode: "replace",223 };224 const reader = createConfigReader(inputs);225 const config = parser.loadConfig(reader);226 expect(config).toStrictEqual(expected);227 });228 it("uses default comment mode if got unsupported value", async () => {229 expect.hasAssertions();230 const inputs = {231 githubToken: "***",232 cloverFile: "clover.xml",233 commentMode: "foo",234 };235 const expected = {236 comment: false,237 check: false,238 githubToken: "***",239 cloverFile: "clover.xml",240 thresholdAlert: 90,241 thresholdWarning: 50,242 statusContext: "Coverage Report",243 commentContext: "Coverage Report",244 commentMode: "replace",245 };246 const reader = createConfigReader(inputs);247 const config = parser.loadConfig(reader);248 expect(config).toStrictEqual(expected);249 });250 Object.entries({251 "on undefined request": undefined,252 "on empty request": {},253 "on missing payload": { payload: undefined },254 "on invalid payload": { payload: {} },255 "on missing pull request": { payload: { pull_request: undefined } },256 "on invalid pull request": { payload: { pull_request: {} } },257 "on missing number": {258 payload: {259 pull_request: { html_url: "https://example.com", head: { sha: "foo" } },260 },261 },262 "on missing pull request URL": {263 payload: { pull_request: { number: 1234, head: { sha: "foo" } } },264 },265 "on missing head info": {266 payload: {267 pull_request: { number: 1234, html_url: "https://example.com" },268 },269 },270 "on invalid head sha": {271 payload: {272 pull_request: {273 number: 1234,274 html_url: "https://example.com",275 head: {},276 },277 },278 },279 }).forEach(([dataset, request]) => {280 it(`fails on invalid webhook request: ${dataset}`, async () => {281 expect.hasAssertions();282 expect(() => {283 parser.parseWebhook(request);284 }).toThrow(new Error("Action supports only pull_request event"));285 });286 });287 it("parses webhook request", async () => {288 expect.hasAssertions();289 const { prNumber, prUrl, sha } = parser.parseWebhook({290 payload: {291 pull_request: {292 number: 1234,293 html_url: "https://example.com",294 head: { sha: "foo" },295 },296 },297 });298 expect(prNumber).toStrictEqual(1234);299 expect(prUrl).toStrictEqual("https://example.com");300 expect(sha).toStrictEqual("foo");301 });302});

Full Screen

Full Screen

transact.test.js

Source:transact.test.js Github

copy

Full Screen

...4const CHARLIE = 'Charlie';5const DENNIS = 'Dennis';6describe('topup', () => {7 it('should reject if amount is less than 1', () => {8 expect.hasAssertions();9 expect(() => topup({username: BOB, amount: 0})).toThrow(10 'amount must be 1 or more'11 );12 });13 it('should reject if amount is missing', () => {14 expect.hasAssertions();15 expect(() => topup({username: ALICE})).toThrow('amount must be present');16 });17 it('should reject if username is missing', () => {18 expect.hasAssertions();19 expect(() => topup({amount: 1})).toThrow('username must be present');20 });21});22describe('transact', () => {23 it('should reject same to and from', () => {24 expect.hasAssertions();25 const txn = {26 from: BOB,27 to: BOB,28 amount: 30,29 };30 expect(() => transact(txn)).toThrow('from and to cannot be the same');31 });32 it('should reject if amount is missing', () => {33 expect.hasAssertions();34 const txn = {35 from: BOB,36 to: ALICE,37 };38 expect(() => transact(txn)).toThrow('amount must be present');39 });40 it('should reject if amount is less than 1', () => {41 expect.hasAssertions();42 const txn = {43 from: BOB,44 to: ALICE,45 amount: 0,46 };47 expect(() => transact(txn)).toThrow('amount must be 1 or more');48 });49});50describe('reconcile', () => {51 it('should ignore unknown transaction type', () => {52 expect.hasAssertions();53 const txns = [54 create(ALICE),55 create(BOB),56 {type: 'unknown type', jibberish: true},57 topup({username: ALICE, amount: 100}),58 topup({username: BOB, amount: 80}),59 ];60 const actual = reconcile(txns);61 const expected = {62 [ALICE]: {63 cash: 100,64 debts: [],65 credits: [],66 },67 [BOB]: {68 cash: 80,69 debts: [],70 credits: [],71 },72 };73 expect(actual).toStrictEqual(expected);74 });75 it('should handle topups', () => {76 expect.hasAssertions();77 const txns = [78 create(ALICE),79 create(BOB),80 topup({username: ALICE, amount: 100}),81 topup({username: BOB, amount: 80}),82 ];83 const actual = reconcile(txns);84 const expected = {85 [ALICE]: {86 cash: 100,87 debts: [],88 credits: [],89 },90 [BOB]: {91 cash: 80,92 debts: [],93 credits: [],94 },95 };96 expect(actual).toStrictEqual(expected);97 });98 it('should handle cash transactions', () => {99 expect.hasAssertions();100 const txns = [101 create(ALICE),102 create(BOB),103 topup({username: ALICE, amount: 100}),104 topup({username: BOB, amount: 80}),105 transact({from: BOB, to: ALICE, amount: 50}),106 ];107 const actual = reconcile(txns);108 expect(actual).toStrictEqual({109 [ALICE]: {110 cash: 150,111 debts: [],112 credits: [],113 },114 [BOB]: {115 cash: 30,116 debts: [],117 credits: [],118 },119 });120 });121 it('should handle transactions with debts stored in sequence', () => {122 expect.hasAssertions();123 const txns = [124 create(ALICE),125 create(BOB),126 topup({username: ALICE, amount: 100}),127 topup({username: BOB, amount: 80}),128 transact({from: BOB, to: ALICE, amount: 150}),129 transact({from: BOB, to: ALICE, amount: 20}),130 ];131 const actual = reconcile(txns);132 expect(actual).toStrictEqual({133 [ALICE]: {134 cash: 180,135 debts: [],136 credits: [137 {username: BOB, amount: 70, id: expect.any(String)},138 {username: BOB, amount: 20, id: expect.any(String)},139 ],140 },141 [BOB]: {142 cash: 0,143 debts: [144 {username: ALICE, amount: 70, id: expect.any(String)},145 {username: ALICE, amount: 20, id: expect.any(String)},146 ],147 credits: [],148 },149 });150 });151 it('should handle debts', () => {152 expect.hasAssertions();153 const txns = [154 create(ALICE),155 create(BOB),156 transact({from: BOB, to: ALICE, amount: 20}),157 topup({username: BOB, amount: 10}),158 ];159 const actual = reconcile(txns);160 expect(actual).toStrictEqual({161 [ALICE]: {162 cash: 10,163 debts: [],164 credits: [{username: BOB, amount: 10, id: expect.any(String)}],165 },166 [BOB]: {167 cash: 0,168 debts: [{username: ALICE, amount: 10, id: expect.any(String)}],169 credits: [],170 },171 });172 });173 it('should repay debts in FIFO order', () => {174 expect.hasAssertions();175 const txns = [176 create(ALICE),177 create(BOB),178 topup({username: ALICE, amount: 50}),179 topup({username: BOB, amount: 20}),180 transact({from: BOB, to: ALICE, amount: 50}),181 transact({from: BOB, to: ALICE, amount: 17}),182 transact({from: BOB, to: ALICE, amount: 8}),183 topup({username: BOB, amount: 40}),184 ];185 const actual = reconcile(txns);186 expect(actual).toStrictEqual({187 [ALICE]: {188 cash: 110,189 debts: [],190 credits: [191 {username: BOB, amount: 7, id: expect.any(String)},192 {username: BOB, amount: 8, id: expect.any(String)},193 ],194 },195 [BOB]: {196 cash: 0,197 debts: [198 {username: ALICE, amount: 7, id: expect.any(String)},199 {username: ALICE, amount: 8, id: expect.any(String)},200 ],201 credits: [],202 },203 });204 });205 it('should pass defined acceptance criteria', () => {206 expect.hasAssertions();207 const txns = [208 create(ALICE),209 create(BOB),210 topup({username: ALICE, amount: 100}),211 topup({username: BOB, amount: 80}),212 transact({from: BOB, to: ALICE, amount: 50}),213 transact({from: BOB, to: ALICE, amount: 100}),214 topup({username: BOB, amount: 30}),215 transact({from: ALICE, to: BOB, amount: 30}),216 topup({username: BOB, amount: 100}),217 ];218 const actual = reconcile(txns);219 expect(actual).toStrictEqual({220 [ALICE]: {...

Full Screen

Full Screen

user-locale.js

Source:user-locale.js Github

copy

Full Screen

...3 */4import userLocaleMiddleware from '../user-locale';5describe( 'User locale middleware', () => {6 it( 'should append the _locale parameter to the path', () => {7 expect.hasAssertions();8 const requestOptions = {9 method: 'GET',10 path: '/wp/v2/posts',11 };12 const callback = ( options ) => {13 expect( options.path ).toBe( '/wp/v2/posts?_locale=user' );14 };15 userLocaleMiddleware( requestOptions, callback );16 } );17 it( 'should append the _locale parameter to path with existing query argument', () => {18 expect.hasAssertions();19 const requestOptions = {20 method: 'GET',21 path: '/wp/v2/posts?foo=bar',22 };23 const callback = ( options ) => {24 expect( options.path ).toBe( '/wp/v2/posts?foo=bar&_locale=user' );25 };26 userLocaleMiddleware( requestOptions, callback );27 } );28 it( 'does not modify existing single _locale parameter in path', () => {29 expect.hasAssertions();30 const requestOptions = {31 method: 'GET',32 path: '/wp/v2/posts?_locale=foo',33 };34 const callback = ( options ) => {35 expect( options.path ).toBe( '/wp/v2/posts?_locale=foo' );36 };37 userLocaleMiddleware( requestOptions, callback );38 } );39 it( 'does not modify existing _locale parameter in path', () => {40 expect.hasAssertions();41 const requestOptions = {42 method: 'GET',43 path: '/wp/v2/posts?foo=bar&_locale=foo',44 };45 const callback = ( options ) => {46 expect( options.path ).toBe( '/wp/v2/posts?foo=bar&_locale=foo' );47 };48 userLocaleMiddleware( requestOptions, callback );49 } );50 it( 'should append the _locale parameter to the url', () => {51 expect.hasAssertions();52 const requestOptions = {53 method: 'GET',54 url: 'http://wp.org/wp-json/wp/v2/posts',55 };56 const callback = ( options ) => {57 expect( options.url ).toBe( 'http://wp.org/wp-json/wp/v2/posts?_locale=user' );58 };59 userLocaleMiddleware( requestOptions, callback );60 } );61 it( 'should append the _locale parameter to url with existing query argument', () => {62 expect.hasAssertions();63 const requestOptions = {64 method: 'GET',65 url: 'http://wp.org/wp-json/wp/v2/posts?foo=bar',66 };67 const callback = ( options ) => {68 expect( options.url ).toBe( 'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=user' );69 };70 userLocaleMiddleware( requestOptions, callback );71 } );72 it( 'does not modify existing single _locale parameter in url', () => {73 expect.hasAssertions();74 const requestOptions = {75 method: 'GET',76 url: 'http://wp.org/wp-json/wp/v2/posts?_locale=foo',77 };78 const callback = ( options ) => {79 expect( options.url ).toBe( 'http://wp.org/wp-json/wp/v2/posts?_locale=foo' );80 };81 userLocaleMiddleware( requestOptions, callback );82 } );83 it( 'does not modify existing _locale parameter in url', () => {84 expect.hasAssertions();85 const requestOptions = {86 method: 'GET',87 url: 'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=foo',88 };89 const callback = ( options ) => {90 expect( options.url ).toBe( 'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=foo' );91 };92 userLocaleMiddleware( requestOptions, callback );93 } );...

Full Screen

Full Screen

writer.test.js

Source:writer.test.js Github

copy

Full Screen

...3const Writer = require('../');4const prettier = require('prettier');5const clean = body => prettier.format(JSON.stringify(body, null, 2));6test('writer produces a feed of dependencies with ids hashed', async () => {7 expect.hasAssertions();8 const writer = new Writer('./test/mock/main.js');9 const result = await getStream(writer.bundle());10 expect(clean(result)).toMatchSnapshot();11});12test('options object passes options on to browserify', async () => {13 expect.hasAssertions();14 const writer = new Writer(['./test/mock/main.js'], {15 debug: true,16 });17 const result = await getStream(writer.bundle());18 expect(clean(result)).toMatchSnapshot();19});20test('bundle option allows getting a bundle instead of a feed', async () => {21 expect.hasAssertions();22 const writer = new Writer('./test/mock/main.js', {}, true);23 const result = await getStream(writer.bundle());24 expect(result).toMatchSnapshot();25});26test('module throws if `files` argument is not an array', async () => {27 expect.hasAssertions();28 const run = () => new Writer(null, {}, true);29 expect(run).toThrowErrorMatchingSnapshot();30});31test('feed is not deduped', async () => {32 expect.hasAssertions();33 const writer = new Writer('./test/mock/no-dedupe.js', {});34 const result = await getStream(writer.bundle());35 expect(clean(result)).toMatchSnapshot();36});37test('different modules with identical source code do produce same id hash.', async () => {38 expect.hasAssertions();39 const writer = new Writer('./test/mock/identical-implementation');40 const feed = await getStream(writer.bundle());41 let identicalHashes = false;42 const hashes = new Map();43 for (const feedItem of feed) {44 if (hashes.has(feedItem.id)) {45 identicalHashes = true;46 break;47 }48 hashes.set(feedItem.id, true);49 }50 expect(identicalHashes).toBe(false);...

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