Best JavaScript code snippet using frisby
api.js
Source:api.js
1const frisby = require("frisby")2const { Joi } = frisby3const link = (endpoint) => `http://api.todolist.local/${endpoint}`4describe("Auth", function () {5 let access_token, refresh_token;6 const user = {7 password: Array(30).fill("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz{}*()!@#$%^&*_-+=").map((x) => { 8 return x[Math.floor(Math.random() * x.length)]9 }).join(''),10 name: "username",11 email: `${Array(30).fill("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz").map((x) => { 12 return x[Math.floor(Math.random() * x.length)]13 }).join('')}@email.com`14 }15 16 it(`POST ${link("auth/register")}`, function () {17 return frisby.post(link("auth/register"), user).expect("jsonTypesStrict", {18 status: Joi.boolean(),19 access_token: Joi.string(),20 refresh_token: Joi.string()21 }).then(res => {22 access_token = res.json.access_token23 refresh_token = res.json.refresh_token24 frisby.globalSetup({25 request: {26 headers: {27 "Authorization": `Bearer ${access_token}`28 }29 }30 })31 })32 })33 34 it(`POST ${link("auth/login")}`, function () {35 return frisby.post(link("auth/login"), user).expect("jsonTypesStrict", {36 status: Joi.boolean(),37 access_token: Joi.string(),38 refresh_token: Joi.string()39 }).then(res => {40 access_token = res.json.access_token41 refresh_token = res.json.refresh_token42 frisby.globalSetup({43 request: {44 headers: {45 "Authorization": `Bearer ${access_token}`46 }47 }48 })49 })50 })51 const prevRefreshToken = refresh_token52 const prevAccessToken = access_token53 it(`POST ${link("auth/refresh-token")}`, () => {54 return frisby.post(link("auth/refresh-token"), {55 refresh_token: refresh_token56 }).expect("status", 200)57 .expect("jsonTypesStrict", {58 status: Joi.boolean(),59 access_token: Joi.string(),60 refresh_token: Joi.string()61 }).then(res => {62 access_token = res.json.access_token63 refresh_token = res.json.refresh_token64 frisby.globalSetup({65 request: {66 headers: {67 "Authorization": `Bearer ${access_token}`68 }69 }70 })71 })72 })73 it("Access token and refresh token changed", () => {74 expect(access_token).not.toBe(prevAccessToken)75 expect(refresh_token).not.toBe(prevRefreshToken)76 })77})78describe("ToDos", function () {79 it(`GET ${link("todo/all")}`, function () {80 return frisby.get(link("todo/all"))81 .expect("status", 200)82 .expect('header', 'Content-Type', 'application/json')83 .expect("jsonTypesStrict", {84 status: Joi.boolean(),85 results: Joi.array()86 })87 })88 it(`POST ${link("todo")}`, function () {89 return frisby.post(link("todo"), {90 text: "new todo"91 })92 .expect("status", 200)93 .expect('header', 'Content-Type', 'application/json')94 .expect("json", "result", {95 text: "new todo"96 })97 })98 it(`POST ${link("todo")} and check result with GET ${link("todo/all")}`, function () {99 return frisby.post(link("todo"), {100 text: "new todo"101 })102 .expect("status", 200)103 .expect('header', 'Content-Type', 'application/json')104 .expect("json", "result", {105 text: "new todo"106 }).then((newTodo) => {107 let id = newTodo.json.result.id108 return frisby.get(link("todo/all"))109 .expect("status", 200)110 .expect('header', 'Content-Type', 'application/json')111 .expect("jsonTypesStrict", {112 status: Joi.boolean(),113 results: Joi.array()114 }).then((todos) => {115 expect(todos.json.results.find((todo) => todo.id == id)).toBeDefined()116 })117 })118 })119 it(`POST ${link("todo")} and check result with GET ${link("todo")}`, function () {120 return frisby.post(link("todo"), {121 text: "new todo"122 })123 .expect("status", 200)124 .expect('header', 'Content-Type', 'application/json')125 .expect("json", "result", {126 text: "new todo"127 }).then((newTodo) => {128 let id = newTodo.json.result.id129 return frisby.get(link(`todo?id=${id}`))130 .expect("status", 200)131 .expect('header', 'Content-Type', 'application/json')132 .expect("json", newTodo.json)133 })134 })135 it(`DELETE ${link("todo")}`, function () {136 return frisby.post(link("todo"), {137 text: "new todo"138 })139 .expect("status", 200)140 .expect('header', 'Content-Type', 'application/json')141 .expect("json", "result", {142 text: "new todo"143 }).then((newTodo) => {144 let id = newTodo.json.result.id145 return frisby.get(link("todo/all"))146 .expect("status", 200)147 .expect('header', 'Content-Type', 'application/json')148 .expect("jsonTypesStrict", {149 status: Joi.boolean(),150 results: Joi.array()151 }).then((todos) => {152 expect(todos.json.results.find((todo) => todo.id == id)).toBeDefined()153 return frisby.del(link(`todo?id=${id}`))154 .expect("status", 200)155 .expect('header', 'Content-Type', 'application/json')156 .expect("jsonTypes", {157 status: Joi.boolean(),158 results: Joi.array()159 }).then((deletedToDo) => {160 let deletedToDoId = deletedToDo.json.results[0].id161 expect(deletedToDoId).toEqual(id)162 return frisby.get(link("todo/all"))163 .expect("status", 200)164 .expect('header', 'Content-Type', 'application/json')165 .expect("jsonTypesStrict", {166 status: Joi.boolean(),167 results: Joi.array()168 }).then((todos) => {169 expect(todos.json.results.find((todo) => todo.id == id)).toBeUndefined()170 })171 })172 })173 })174 })175 it(`PATCH ${link("todo")}`, function () {176 return frisby.post(link("todo"), {177 text: "new todo"178 })179 .expect("status", 200)180 .expect('header', 'Content-Type', 'application/json')181 .expect("json", "result", {182 text: "new todo"183 }).then((newTodo) => {184 let id = newTodo.json.result.id185 return frisby.get(link("todo/all"))186 .expect("status", 200)187 .expect('header', 'Content-Type', 'application/json')188 .expect("jsonTypesStrict", {189 status: Joi.boolean(),190 results: Joi.array()191 }).then((todos) => {192 expect(todos.json.results.find((todo) => todo.id == id)).toBeDefined()193 return frisby.patch(link(`todo`), {194 id,195 text: "updated text"196 })197 .expect("status", 200)198 .expect('header', 'Content-Type', 'application/json')199 .expect("json", {200 status: true,201 result: {202 id,203 text: "updated text"204 }205 }).then((updatedToDo) => {206 let updatedToDoId = updatedToDo.json.result.id207 expect(updatedToDoId).toEqual(id)208 return frisby.get(link("todo/all"))209 .expect("status", 200)210 .expect('header', 'Content-Type', 'application/json')211 .expect("jsonTypesStrict", {212 status: Joi.boolean(),213 results: Joi.array()214 }).then((todos) => {215 expect(todos.json.results.find((todo) => todo.id == id && todo.text == "updated text")).toBeDefined()216 })217 })218 })219 })220 })...
expects_jsonTypes_spec.js
Source:expects_jsonTypes_spec.js
1'use strict';2const frisby = require('../src/frisby');3const Joi = frisby.Joi;4const mocks = require('./fixtures/http_mocks');5const testHost = 'http://api.example.com';6describe('expect(\'jsonTypes\')', function() {7 it('should match exact JSON', function(doneFn) {8 mocks.use(['getUser1']);9 frisby.fetch(testHost + '/users/1')10 .expect('jsonTypes', {11 id: Joi.number(),12 email: Joi.string()13 })14 .done(doneFn);15 });16 it('should error with extra key', function(doneFn) {17 mocks.use(['getUser1']);18 frisby.fetch(testHost + '/users/1')19 .expectNot('jsonTypes', {20 id: Joi.number().required(),21 id2: Joi.number().required(),22 email: Joi.string().email().required()23 })24 .done(doneFn);25 });26 it('should error with missing key', function(doneFn) {27 mocks.use(['getUser1']);28 frisby.fetch(testHost + '/users/1')29 .expectNot('jsonTypes', {30 email: Joi.number()31 })32 .done(doneFn);33 });34 it('should error with matching keys, but incorrect value types', function(doneFn) {35 mocks.use(['getUser1']);36 frisby.fetch(testHost + '/users/1')37 .expectNot('json', {38 id: Joi.string(),39 email: Joi.number()40 })41 .done(doneFn);42 });43 it('should match from data via fromJSON', function(doneFn) {44 frisby.fromJSON({45 foo: 'bar'46 })47 .expect('jsonTypes', {48 foo: Joi.string()49 })50 .done(doneFn);51 });52 it('should match JSON in using provided path', function(doneFn) {53 frisby.fromJSON({54 one: {55 two: {56 three: 357 }58 }59 })60 .expect('jsonTypes', 'one.two', {61 three: Joi.number()62 })63 .done(doneFn);64 });65 it('should match JSON with nested structure and no path', function(doneFn) {66 frisby.fromJSON({67 one: {68 foo: 'bar',69 two: {70 three: 371 }72 }73 })74 .expect('jsonTypes', {75 one: {76 foo: Joi.string(),77 two: {78 three: Joi.number()79 }80 }81 })82 .done(doneFn);83 });84 it('should match JSON with nested structure and single path', function(doneFn) {85 frisby.fromJSON({86 one: {87 foo: 'bar',88 two: {89 three: 390 }91 }92 })93 .expect('jsonTypes', 'one', {94 foo: Joi.string(),95 two: {96 three: Joi.number()97 }98 })99 .done(doneFn);100 });101 it('should fail JSON with nested structure and incorrect type', function(doneFn) {102 frisby.fromJSON({103 one: {104 foo: 'bar',105 }106 })107 .expectNot('jsonTypes', 'one', {108 foo: Joi.number()109 })110 .done(doneFn);111 });112 it('should validate JSON with single value', function(doneFn) {113 frisby.fromJSON({114 one: {115 foo: 'bar',116 two: {117 three: 3118 }119 }120 })121 .expect('jsonTypes', 'one.two.three', Joi.number())122 .done(doneFn);123 });124 it('should match JSON with array of objects and asterisk path (each)', function (doneFn) {125 frisby.fromJSON({126 offers: [{name: 'offer1'}, {name: 'offer2'}]127 })128 .expect('jsonTypes', 'offers', Joi.array())129 .expect('jsonTypes', 'offers.*', {130 name: Joi.string()131 })132 .done(doneFn);133 });134 it('should ignore additional JSON keys', function (doneFn) {135 frisby.fromJSON({136 name: 'john',137 foo: 'bar'138 })139 .expect('jsonTypes', {140 name: Joi.string()141 })142 .done(doneFn);143 });144 it('should override joi global options', function (doneFn) {145 frisby.setup({ request: { inspectOnFailure: false } })146 .fromJSON('1')147 .expect('jsonTypes', Joi.number())148 .catch(function (err) {149 fail('this function will never be called.');150 })151 .expect('jsonTypes', Joi.number().options({152 convert: false153 }))154 .then(function (res) {155 fail('this function will never be called.');156 })157 .catch(function (err) {158 })159 .done(doneFn);160 });161 it('should output path in error message (1)', function (doneFn) {162 frisby.setup({ request: { inspectOnFailure: false } })163 .fromJSON({164 name: 'john'165 })166 .expect('jsonTypes', 'name', Joi.number())167 .catch(function (err) {168 expect(err.message).toMatch(/\bname\b/);169 expect(err.message).not.toMatch(/\bvalue\b/);170 })171 .done(doneFn);172 });173 it('should output path in error message (2)', function (doneFn) {174 frisby.setup({ request: { inspectOnFailure: false } })175 .fromJSON({176 user: {177 name: 'john'178 }179 })180 .expect('jsonTypes', 'user.name', Joi.number())181 .catch(function (err) {182 expect(err.message).toMatch(/\buser\.name\b/);183 expect(err.message).not.toMatch(/\bvalue\b/);184 })185 .done(doneFn);186 });187 it('should output default label in error message', function (doneFn) {188 frisby.setup({ request: { inspectOnFailure: false } })189 .fromJSON('john')190 .expect('jsonTypes', Joi.number())191 .catch(function (err) {192 expect(err.message).toMatch(/\bvalue\b/);193 })194 .done(doneFn);195 });196 it('should error in undefined JSON', function (doneFn) {197 frisby.setup({ request: { inspectOnFailure: false } })198 .fromJSON(undefined)199 .expect('jsonTypes', Joi.string())200 .catch(function (err) {201 expect(err.name).toBe('Error');202 expect(err.message).toContain('jsonBody is undefined');203 })204 .done(doneFn);205 });206});207describe('expect(\'jsonTypesStrict\')', function() {208 it('should error on additional JSON keys not accounted for', function (doneFn) {209 frisby.fromJSON({210 name: 'john',211 foo: 'bar'212 })213 .expect('jsonTypesStrict', {214 name: Joi.string(),215 foo: Joi.string()216 })217 .expectNot('jsonTypesStrict', {218 name: Joi.string()219 })220 .done(doneFn);221 });...
users.spec.js
Source:users.spec.js
1import frisby from "frisby";2const Joi = frisby.Joi; // Frisby exposes Joi for convenience3const address = Joi.object({4 street: Joi.string().required(),5 suite: Joi.string().required(),6 city: Joi.string().required(),7 zipcode: Joi.string().required(),8 geo: {9 lat: Joi.string().required(),10 lng: Joi.string().required(),11 },12});13const company = Joi.object({14 name: Joi.string(),15 catchPhrase: Joi.string(),16 bs: Joi.string(),17});18const user = Joi.object({19 id: Joi.number().required(),20 name: Joi.string().required(),21 username: Joi.string().required(),22 email: Joi.string().email(),23 phone: Joi.string().required(),24 website: Joi.string().uri({ allowRelative: true }).required(),25 address,26 company,27});28describe("/users routes", () => {29 describe("GET /", () => {30 it("should return valid users list", function () {31 return frisby32 .get("http://localhost:3000/users")33 .expect("status", 200)34 .expect("jsonTypesStrict", "*", user);35 });36 });37 describe("GET /:id", () => {38 it("should return valid user", function () {39 return frisby40 .get("http://localhost:3000/users/1")41 .expect("status", 200)42 .expect("jsonTypesStrict", user);43 });44 it("should return 404 if user doesn't exist", function () {45 return frisby46 .get("http://localhost:3000/users/999")47 .expect("status", 404)48 .expect("bodyContains", "Not found");49 });50 });...
Using AI Code Generation
1const frisby = require('frisby');2const Joi = frisby.Joi;3const { jsonTypesStrict } = frisby;4frisby.globalSetup({5 request: {6 headers: {7 },8 },9});10 .expect('status', 200)11 .expect('jsonTypesStrict', {12 id: Joi.number().required(),13 name: Joi.string().required(),14 email: Joi.string().required(),15 password: Joi.string().required(),16 createdAt: Joi.string().required(),17 updatedAt: Joi.string().required(),18 })19 .done();20const frisby = require('frisby');21const Joi = frisby.Joi;22const { jsonStrict } = frisby;23frisby.globalSetup({24 request: {25 headers: {26 },27 },28});29 .expect('status', 200)30 .expect('jsonStrict', {
Using AI Code Generation
1var frisby = require('frisby');2var jsonTypesStrict = frisby.jsonTypesStrict;3frisby.create('Test API')4.expectStatus(200)5.expectJSONTypesStrict({6})7.toss();
Using AI Code Generation
1var frisby = require('frisby');2frisby.create('Test JSON types strict')3 .expectStatus(200)4 .expectHeaderContains('content-type', 'application/json')5 .expectJSONTypesStrict({6 })7.toss();8var frisby = require('frisby');9frisby.create('Test JSON types')10 .expectStatus(200)11 .expectHeaderContains('content-type', 'application/json')12 .expectJSONTypes({13 })14.toss();15var frisby = require('frisby');16frisby.create('Test JSON')17 .expectStatus(200)18 .expectHeaderContains('content-type', 'application/json')19 .expectJSON({20 clouds: {all: 90},21 coord: {lon: -0.13, lat: 51.51},22 main: {temp: 289.71, temp_min: 287.04, temp_max: 292.04, pressure: 1019, sea_level: 1028.62, grnd_level: 1019, humidity: 93},23 sys: {message: 0.0038
Using AI Code Generation
1var frisby = require('frisby');2var fs = require('fs');3var json = fs.readFileSync('test.json');4var data = JSON.parse(json);5frisby.create('Test API')6 .expectStatus(200)7 .jsonTypesStrict(data)8 .toss();9{10}11Your name to display (optional):12Your name to display (optional):13Your name to display (optional):
Using AI Code Generation
1var frisby = require('frisby');2frisby.create('Test for jsonTypesStrict')3.expectStatus(200)4.expectHeaderContains('content-type', 'application/json')5.expectJSONTypes({6 user: {7 }8})9.toss();10var frisby = require('frisby');11frisby.create('Test for jsonTypesStrict')12.expectStatus(200)13.expectHeaderContains('content-type', 'application/json')14.expectJSONTypes({15 user: {16 }17})18.toss();19var frisby = require('frisby');20frisby.create('Test for jsonTypesStrict')21.expectStatus(200)22.expectHeaderContains('content-type', 'application/json')23.expectJSONTypes({24 user: {25 }26})27.toss();28var frisby = require('frisby');29frisby.create('Test for jsonTypesStrict')30.expectStatus(200)31.expectHeaderContains('content-type', 'application/json')32.expectJSONTypes({33 user: {34 }35})36.toss();37var frisby = require('frisby');38frisby.create('Test for jsonTypesStrict')39.expectStatus(200)40.expectHeaderContains('content-type', 'application/json')
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!