Best JavaScript code snippet using appium-xcuitest-driver
sse-channel.test.js
Source:sse-channel.test.js
...13 this.timeout(5000);14 var port = process.env.TESTING_PORT || 6775;15 var host = 'http://localhost:' + port;16 var server, channel, es, path = '/sse';17 function initServer(opts) {18 var tmp = serverInit(merge({}, { port: port, path: path }, opts || {}));19 server = tmp.server;20 channel = tmp.channel;21 return channel;22 }23 afterEach(function(done) {24 if (es) {25 es.close();26 }27 if (channel) {28 channel.close();29 }30 if (server && server.close) {31 server.close(done);32 return;33 }34 done();35 });36 it('can be constructed without options', function() {37 assert.doesNotThrow(function() {38 channel = new SseChannel();39 }, 'should not throw if constructed without options');40 });41 it('can broadcast simple message', function(done) {42 initServer();43 var text = 'First event!';44 channel.on('connect', function() {45 channel.send(text);46 });47 es = new EventSource(host + path);48 es.onmessage = function(e) {49 assert.strictEqual(e.data, text);50 done();51 };52 });53 it('represents messages without event name as "message"', function(done) {54 initServer();55 channel.on('connect', function() {56 channel.send('Moo');57 });58 es = new EventSource(host + path);59 es.onmessage = function(e) {60 assert.strictEqual(e.type, 'message');61 done();62 };63 });64 it('addClient calls the specified callback when finished serving initial data', function(done) {65 initServer({66 addClientCallback: function(err) {67 assert.ifError(err);68 done();69 }70 });71 es = new EventSource(host + path);72 });73 it('can send messages to specific clients', function(done) {74 initServer();75 var privText = 'Private', count = 0;76 channel.on('connect', function(chan, req, res) {77 // Wait for two clients to connect78 if (++count !== 2) {79 return;80 }81 chan.send({ id: 1, data: privText }, [res]);82 });83 // Should not receive the message84 es = new EventSource(host + path);85 es.onmessage = function(e) {86 if (e.data === privText) {87 throw new Error('EventSource client #1 should not receive the private message');88 }89 };90 es.onopen = function() {91 // Should receive the message92 var es2 = new EventSource(host + path);93 es2.onmessage = function(e) {94 assert.strictEqual(e.data, privText);95 es2.close();96 // Ensure the history is not populated with the "private" message97 var pubText = 'Public';98 channel.send({ id: 2, data: pubText });99 var es3 = new EventSource(host + path, { headers: { 'Last-Event-Id': '0' } });100 es3.onmessage = function(e3) {101 es3.close();102 if (e3.data === privText) {103 throw new Error('"Private" message found in history');104 }105 assert.strictEqual(e3.data, pubText);106 done();107 };108 };109 };110 });111 it('can broadcast messages with ID and type', function(done) {112 initServer();113 var data = 'Reign in Citra';114 channel.on('connect', function() {115 channel.send({ event: 'drink', data: data, id: 1337 });116 });117 es = new EventSource(host + path);118 es.addEventListener('drink', function(e) {119 assert.strictEqual(e.lastEventId, '1337');120 assert.strictEqual(e.type, 'drink');121 assert.strictEqual(e.data, data);122 done();123 }, false);124 });125 it('can tell clients how long they should wait before reconnecting', function(done) {126 initServer({ retryTimeout: 3000 });127 channel.on('connect', function() {128 var disconnected;129 // Tell clients to reconnect after approx 75 milliseconds130 var retryTime = 75;131 channel.retry(retryTime);132 // Remove the 'connect'-listener (for testing purposes, since we re-apply it below)133 channel.removeAllListeners();134 // Add a new connect listener that we can use to assert with135 channel.on('connect', function() {136 var timeUsed = Date.now() - disconnected;137 assert.ok(138 timeUsed > (retryTime * 0.25) && timeUsed < (retryTime * 1.75),139 'Client did not reconnect after ~' + retryTime + 'ms ' +140 '(reconnected after ' + timeUsed + 'ms)'141 );142 done();143 });144 // Disconnect all clients on the channel145 disconnected = Date.now();146 channel.close();147 });148 es = new EventSource(host + path);149 });150 it('can provide a history of events if client is disconnected', function(done) {151 initServer();152 var id = 1337, msgCount = 0;153 for (var i = 0; i < 6; i++) {154 channel.send({ id: ++id, data: 'Event #' + id });155 }156 es = new EventSource(host + path, { headers: { 'Last-Event-Id': '1337' } });157 es.onmessage = function(e) {158 if (++msgCount !== 6) {159 return;160 }161 // Data should correspond to the last message we sent162 assert.strictEqual(e.data, 'Event #' + id);163 done();164 };165 });166 it('can provide a history of events through "evs_last_event_id"-query param', function(done) {167 initServer();168 var id = 1337, msgCount = 0;169 for (var i = 0; i < 6; i++) {170 channel.send({ id: ++id, data: 'Event #' + id });171 }172 es = new EventSource(host + path + '?evs_last_event_id=1337');173 es.onmessage = function(e) {174 if (++msgCount !== 6) {175 return;176 }177 assert.strictEqual(e.data, 'Event #' + id);178 done();179 };180 });181 it('can provide a history of events through "lastEventId"-query param', function(done) {182 initServer();183 var id = 1337, msgCount = 0;184 for (var i = 0; i < 6; i++) {185 channel.send({ id: ++id, data: 'Event #' + id });186 }187 es = new EventSource(host + path + '?lastEventId=1337');188 es.onmessage = function(e) {189 if (++msgCount !== 6) {190 return;191 }192 assert.strictEqual(e.data, 'Event #' + id);193 done();194 };195 });196 it('does not send history by default', function(done) {197 initServer();198 var id = 1337, msgCount = 0;199 for (var i = 0; i < 6; i++) {200 channel.send({ id: ++id, data: 'Event #' + id });201 }202 es = new EventSource(host + path);203 es.onopen = function() {204 channel.send('Boom');205 };206 es.onmessage = function(e) {207 if (++msgCount === 1) {208 assert.strictEqual(e.data, 'Boom');209 done();210 }211 };212 });213 it('sends the right slice of the history', function(done) {214 initServer();215 var id = 1337, msgCount = 0, lastMsg;216 for (var i = 0; i < 6; i++) {217 channel.send({ id: ++id, data: 'Event #' + id });218 }219 var assertMsgCount = debounce(function() {220 assert.strictEqual(msgCount, 4);221 assert.strictEqual(lastMsg.data, 'Event #' + id);222 done();223 }, 25);224 es = new EventSource(host + path + '?lastEventId=1339');225 es.onmessage = function(e) {226 msgCount++;227 lastMsg = e;228 assertMsgCount();229 };230 });231 it('only includes the latest event with the same ID', function(done) {232 initServer();233 var id = 1337, msgCount = 0, lastMsg;234 for (var i = 0; i < 6; i++) {235 channel.send({ id: 1337, data: 'Event #' + id });236 }237 var assertMsgCount = debounce(function() {238 assert.strictEqual(msgCount, 1);239 assert.strictEqual(lastMsg.data, 'Event #' + id);240 done();241 }, 25);242 es = new EventSource(host + path + '?lastEventId=1330');243 es.onmessage = function(e) {244 msgCount++;245 lastMsg = e;246 assertMsgCount();247 };248 });249 it('can be configured to a specific max history size', function(done) {250 initServer({ historySize: 5 });251 var id = 100, msgCount = 0, lastMsg;252 for (var i = 0; i < 100; i++) {253 channel.send({ id: ++id, data: 'Event #' + id });254 }255 var assertMsgCount = debounce(function() {256 assert.strictEqual(msgCount, 5);257 assert.strictEqual(lastMsg.data, 'Event #' + id);258 done();259 }, 25);260 es = new EventSource(host + path + '?lastEventId=110');261 es.onmessage = function(e) {262 msgCount++;263 lastMsg = e;264 assertMsgCount();265 };266 });267 it('can be given an array of events to pre-populate with', function(done) {268 var msgs = [], id = 1337;269 for (var i = 0; i < 10; i++) {270 msgs.push({ id: ++id, data: 'Event #' + id });271 }272 initServer({ historySize: 5, history: msgs });273 var msgCount = 0, lastMsg;274 var assertMsgCount = debounce(function() {275 assert.strictEqual(msgCount, 5);276 assert.strictEqual(lastMsg.data, 'Event #' + id);277 done();278 }, 25);279 es = new EventSource(host + path + '?lastEventId=1');280 es.onmessage = function(e) {281 msgCount++;282 lastMsg = e;283 assertMsgCount();284 };285 });286 it('provides a correct number of connections on channel', function(done) {287 initServer();288 var connections = channel.getConnectionCount();289 assert.strictEqual(connections, 0, 'Initial connection count should be 0, got ' + connections);290 es = new EventSource(host + path);291 es.onopen = function() {292 connections = channel.getConnectionCount();293 assert.strictEqual(294 connections,295 1,296 'Connection count after opening first connection should be 1, got ' + connections297 );298 process.nextTick(function() {299 var es2 = new EventSource(host + path);300 es2.onopen = function() {301 connections = channel.getConnectionCount();302 assert.strictEqual(303 connections,304 2,305 'Connection count after opening second connection should be 2, got ' + connections306 );307 es2.close();308 setTimeout(function() {309 connections = channel.getConnectionCount();310 assert.strictEqual(311 connections,312 1,313 'Connection count after disconnecting one session should be 1, got ' + connections314 );315 done();316 }, 25);317 };318 });319 };320 });321 it('sends automatic pings', function(done) {322 // We'll want to use some custom logic for the channel here323 var interval = 25;324 initServer({ pingInterval: interval });325 var opts = url.parse(host + path);326 opts.headers = { Accept: 'text/event-stream' };327 var req = http.request(opts, function(res) {328 var buf = '';329 res.on('data', function(chunk) {330 buf += chunk.toString();331 });332 setTimeout(function() {333 req.abort();334 assert.ok(335 buf.match(/\:\n/g).length >= 5,336 'Expected at least 5 pings within ' + (interval * 7) + 'ms'337 );338 done();339 }, interval * 7);340 });341 req.setNoDelay(true);342 req.end();343 });344 it('sends "preamble" if client requests it', function(done) {345 initServer();346 var opts = url.parse(host + path + '?evs_preamble=1');347 opts.headers = { Accept: 'text/event-stream' };348 var req = http.request(opts, function(res) {349 var buf = '';350 res.on('data', function(chunk) {351 buf += chunk.toString();352 if (buf.match(/\-{3}\n/)) {353 assert.ok(354 buf.match(/\:\-{2056,}/),355 'Preamble of 2kb not present in response'356 );357 req.abort();358 done();359 }360 });361 });362 req.setNoDelay(true);363 req.end();364 });365 it('can auto-encode data as JSON', function(done) {366 initServer({ jsonEncode: true });367 channel.on('connect', function() {368 channel.send({ data: ['foo', 'bar'] });369 channel.send({ data: { foo: 'bar' } });370 channel.send({ data: 'Foobar' });371 });372 es = new EventSource(host + path);373 es.onmessage = function(e) {374 var data = JSON.parse(e.data);375 if (Array.isArray(data)) {376 // Assume first message377 assert.strictEqual(data[0], 'foo');378 assert.strictEqual(data[1], 'bar');379 } else if (typeof data === 'string') {380 // Assume second message381 assert.strictEqual(data, 'Foobar');382 } else if (typeof data === 'object' && !data.type) {383 // Assume object, third message384 assert.strictEqual(data.foo, 'bar');385 done();386 }387 };388 });389 it('does not JSON-encode data by default', function(done) {390 initServer();391 channel.on('connect', function() {392 channel.send({ data: { foo: 'bar' } });393 });394 es = new EventSource(host + path);395 es.onmessage = function(e) {396 assert.strictEqual(e.data, '[object Object]');397 done();398 };399 });400 it('send string messages as JSON if jsonEncode is enabled', function(done) {401 initServer({ jsonEncode: true });402 channel.on('connect', function() {403 channel.send('foobar');404 });405 es = new EventSource(host + path);406 es.onmessage = function(e) {407 assert.strictEqual(e.data, '"foobar"');408 done();409 };410 });411 it('send string messages as plain string if jsonEncode is disabled', function(done) {412 initServer();413 channel.on('connect', function() {414 channel.send('foobar');415 });416 es = new EventSource(host + path);417 es.onmessage = function(e) {418 assert.strictEqual(e.data, 'foobar');419 done();420 };421 });422 it('treats missing data property as empty string', function(done) {423 initServer();424 channel.on('connect', function() {425 channel.send({ id: 1337 });426 });427 es = new EventSource(host + path);428 es.onmessage = function(e) {429 assert.strictEqual(e.data, '');430 done();431 };432 });433 it('handles multi-line strings properly', function(done) {434 initServer();435 var text = [436 'Line 1',437 'Line 2',438 '',439 'Line 4',440 'Line 5\n\n\n',441 'Line ..9?'442 ].join('\n');443 channel.on('connect', function() {444 channel.send(text);445 });446 es = new EventSource(host + path);447 es.onmessage = function(e) {448 assert.strictEqual(e.data, text);449 done();450 };451 });452 it('sends initial retry-timeout if specified in channel config', function(done) {453 initServer({ retryTimeout: 3000 });454 var opts = url.parse(host + path);455 opts.headers = { Accept: 'text/event-stream' };456 var req = http.request(opts, function(res) {457 var buf = '';458 res.on('data', function(chunk) {459 buf += chunk.toString();460 if (buf.length >= 17) {461 assert.ok(buf.indexOf('retry: 3000\n') > -1);462 req.abort();463 done();464 }465 });466 });467 req.setNoDelay(true);468 req.end();469 });470 it('single event can contain event name, retry time, id and data', function(done) {471 initServer();472 var opts = url.parse(host + path);473 opts.headers = { Accept: 'text/event-stream' };474 var req = http.request(opts, function(res) {475 var buf = '';476 res.on('data', function(chunk) {477 buf += chunk.toString();478 if (buf.indexOf('Citra') > -1) {479 assert.ok(buf.indexOf('\nevent: drink\n') > -1);480 assert.ok(buf.indexOf('\nretry: 1800\n') > -1);481 assert.ok(buf.indexOf('\nid: 1337\n') > -1);482 assert.ok(buf.indexOf('\ndata: Reign in Citra\n') > -1);483 req.abort();484 done();485 }486 });487 channel.send({ retry: 1800, id: 1337, event: 'drink', data: 'Reign in Citra' });488 });489 req.setNoDelay(true);490 req.end();491 });492 it('calls flush() after writes if the method exists on response', function(done) {493 // Initialize a server with a custom `flush()` method added on each incoming request,494 // mimicking the `compression` middleware. Check that we call `flush()`:495 // - On connect, after the initial headers, retry, and preamble has been written496 // - After "missed events" have been sent (once)497 // - After each broadcast498 var flushes = 0;499 initServer({500 flush: function() {501 flushes++;502 },503 history: [504 { id: 1338, data: 'Event #1338' },505 { id: 1339, data: 'Event #1339' }506 ]507 });508 es = new EventSource(host + path + '?lastEventId=1337&evs_preamble=1');509 es.onopen = function() {510 channel.send('We set sail from the sweet cove of Cork');511 channel.send('With seven million barrels of porter');512 };513 es.onmessage = runAfter(4, function() {514 assert.strictEqual(flushes, 4);515 done();516 });517 });518 it('emits connect/disconnect/message events', function(done) {519 channel = initServer();520 var connections = [];521 var status = {522 connect: 0,523 disconnect: 0,524 message: 0525 };526 channel.on('connect', function(chan, req, res) {527 assert.strictEqual(channel, chan);528 assert.ok(req instanceof http.IncomingMessage);529 assert.ok(res instanceof http.ServerResponse);530 if (++status.connect === 2) {531 channel.send('foobar');532 channel.send({ data: 'barfoo' }, [res]);533 }...
pergunta.test.js
Source:pergunta.test.js
...11 });12 return headers['set-cookie'];13};14test('api.perguntas.create', async t => {15 const fastify = await initServer(t);16 const { _id: usuarioId } = await seed.entidades.usuario();17 const perguntaData = seed.fixtures.pergunta({ usuarioId: usuarioId.toString() });18 const { statusCode } = await fastify.inject({19 url: '/api/perguntas',20 method: 'POST',21 payload: perguntaData,22 });23 t.same(statusCode, 200);24 t.end();25});26test('api.perguntas.create', async t => {27 const fastify = await initServer(t);28 const { _id: usuarioId } = await seed.entidades.usuario();29 const perguntaData = seed.fixtures.pergunta({ usuarioId: usuarioId.toString() });30 const { statusCode } = await fastify.inject({31 url: '/api/perguntas',32 method: 'POST',33 payload: perguntaData,34 });35 t.same(statusCode, 200);36 t.end();37});38test('api.perguntas.create: cadastra com referência para usuário inválida', async t => {39 const fastify = await initServer(t);40 const usuarioId = randomObjectId();41 const perguntaData = seed.fixtures.pergunta({ usuarioId: usuarioId.toString() });42 const { statusCode, payload } = await fastify.inject({43 url: '/api/perguntas',44 method: 'POST',45 payload: perguntaData,46 });47 const { message } = JSON.parse(payload);48 t.same(message, 'Referência para usuário inválida');49 t.same(statusCode, 400);50 t.end();51});52test('api.perguntas.delete', async t => {53 const fastify = await initServer(t);54 const usuario = seed.fixtures.usuario();55 const { _id: usuarioId } = await seed.entidades.usuario(usuario);56 const pergunta = await seed.entidades.pergunta({ usuarioId });57 const cookie = await getCookie({ fastify, payload: { username: usuario.username, password: usuario.password } });58 const { statusCode } = await fastify.inject({59 url: `/api/perguntas/${pergunta._id}`,60 method: 'DELETE',61 headers: { cookie },62 });63 t.same(statusCode, 200);64 t.end();65});66test('api.perguntas.delete: passa id inválido', async t => {67 const fastify = await initServer(t);68 const { statusCode, payload } = await fastify.inject({69 url: `/api/perguntas/${randomObjectId()}`,70 method: 'DELETE',71 });72 const { message } = JSON.parse(payload);73 t.same(message, 'Not Found');74 t.same(statusCode, 404);75 t.end();76});77test('api.perguntas.update: somente usuario que postou a pergunta pode deletá-la', async t => {78 const fastify = await initServer(t);79 const usuario1 = await seed.entidades.usuario();80 const usuario2 = seed.fixtures.usuario();81 await seed.entidades.usuario(usuario2);82 const pergunta = await seed.entidades.pergunta({ usuarioId: usuario1._id });83 const cookie = await getCookie({ fastify, payload: { username: usuario2.username, password: usuario2.password } });84 const { statusCode, payload } = await fastify.inject({85 url: `/api/perguntas/${pergunta._id}`,86 method: 'DELETE',87 headers: { cookie },88 });89 const { message } = JSON.parse(payload);90 t.same(message, 'Somente o usuário que postou a pergunta pode deletá-la');91 t.same(statusCode, 401);92 t.end();93});94test('api.perguntas.find', async t => {95 const fastify = await initServer(t);96 const pergunta = await seed.entidades.pergunta();97 const { statusCode } = await fastify.inject({98 url: `/api/perguntas/${pergunta._id}`,99 method: 'GET',100 });101 t.same(statusCode, 200);102 t.end();103});104test('api.perguntas.find: passa id inválido', async t => {105 const fastify = await initServer(t);106 const { statusCode, payload } = await fastify.inject({107 url: `/api/perguntas/${randomObjectId()}`,108 method: 'GET',109 });110 const { message } = JSON.parse(payload);111 t.same(message, 'Not Found');112 t.same(statusCode, 404);113 t.end();114});115test('api.perguntas.update', async t => {116 const fastify = await initServer(t);117 const usuario = seed.fixtures.usuario();118 const { _id: usuarioId } = await seed.entidades.usuario(usuario);119 const pergunta = await seed.entidades.pergunta({ usuarioId });120 const alteracoes = { descricao: 'pergunta atualizado' };121 const cookie = await getCookie({ fastify, payload: { username: usuario.username, password: usuario.password } });122 const { statusCode } = await fastify.inject({123 url: `/api/perguntas/${pergunta._id}`,124 method: 'POST',125 payload: alteracoes,126 headers: { cookie },127 });128 t.same(statusCode, 200);129 t.end();130});131test('api.perguntas.update: passa id inválido', async t => {132 const fastify = await initServer(t);133 const { statusCode, payload } = await fastify.inject({134 url: `/api/perguntas/${randomObjectId()}`,135 method: 'POST',136 payload: {},137 });138 const { message } = JSON.parse(payload);139 t.same(message, 'Not Found');140 t.same(statusCode, 404);141 t.end();142});143test('api.perguntas.update: tenta atualizar usuarioId', async t => {144 const fastify = await initServer(t);145 const usuario = seed.fixtures.usuario();146 const { _id: usuarioId } = await seed.entidades.usuario(usuario);147 const pergunta = await seed.entidades.pergunta({ usuarioId });148 const alteracoes = { usuarioId: 'nao pode migao' };149 const cookie = await getCookie({ fastify, payload: { username: usuario.username, password: usuario.password } });150 const { statusCode, payload } = await fastify.inject({151 url: `/api/perguntas/${pergunta._id}`,152 method: 'POST',153 payload: alteracoes,154 headers: { cookie },155 });156 const { message } = JSON.parse(payload);157 t.same(message, 'Referência de usuário da pergunta não deve ser alterada');158 t.same(statusCode, 400);159 t.end();160});161test('api.perguntas.update: somente usuario que postou a pergunta pode editá-la', async t => {162 const fastify = await initServer(t);163 const usuario1 = await seed.entidades.usuario();164 const usuario2 = seed.fixtures.usuario();165 await seed.entidades.usuario(usuario2);166 const pergunta = await seed.entidades.pergunta({ usuarioId: usuario1._id });167 const alteracoes = { descricao: 'pergunta atualizado' };168 const cookie = await getCookie({ fastify, payload: { username: usuario2.username, password: usuario2.password } });169 const { statusCode, payload } = await fastify.inject({170 url: `/api/perguntas/${pergunta._id}`,171 method: 'POST',172 payload: alteracoes,173 headers: { cookie },174 });175 const { message } = JSON.parse(payload);176 t.same(message, 'Somente o usuário que postou a pergunta pode editá-la');177 t.same(statusCode, 401);178 t.end();179});180test('api.perguntas.usuarios', async t => {181 const fastify = await initServer(t);182 const usuario = await seed.entidades.usuario();183 await seed.entidades.pergunta({ usuarioId: usuario._id });184 const { statusCode } = await fastify.inject({185 url: `/api/perguntas/usuarios/${usuario._id}`,186 method: 'GET',187 });188 t.same(statusCode, 200);189 t.end();190});191test('api.perguntas.search: pesquisa por tags', async t => {192 const fastify = await initServer(t);193 const { _id: usuarioId } = await seed.entidades.usuario();194 const perguntaData = seed.fixtures.pergunta({ usuarioId, tags: ['teste1', 'teste2'] });195 await fastify.core.models.pergunta.create(perguntaData);196 const filter = utils.serialize({ tags: ['teste1', 'teste2'] });197 const { statusCode, payload } = await fastify.inject({198 url: '/api/perguntas/search?' + filter,199 method: 'GET',200 });201 const { total } = JSON.parse(payload);202 t.same(statusCode, 200);203 t.same(total, 1);204 t.end();205});206test('api.perguntas.search: pesquisa por uma única tag', async t => {207 const fastify = await initServer(t);208 const { _id: usuarioId } = await seed.entidades.usuario();209 const perguntaData = seed.fixtures.pergunta({ usuarioId, tags: ['teste1', 'teste2'] });210 await fastify.core.models.pergunta.create(perguntaData);211 const filter = utils.serialize({ tags: 'teste1' });212 const { statusCode, payload } = await fastify.inject({213 url: '/api/perguntas/search?' + filter,214 method: 'GET',215 });216 const { total } = JSON.parse(payload);217 t.same(statusCode, 200);218 t.same(total, 1);219 t.end();220});221test('api.perguntas.search: pesquisa por keyword', async t => {222 const fastify = await initServer(t);223 const keyword = 'titulo esotérico';224 await seed.entidades.pergunta({ titulo: 'um titulo esotérico aÃ' });225 const filter = utils.serialize({ keyword });226 const { statusCode, payload } = await fastify.inject({227 url: '/api/perguntas/search?' + filter,228 method: 'GET',229 });230 const { total } = JSON.parse(payload);231 t.same(statusCode, 200);232 t.same(total, 1);233 t.end();234});235test('api.perguntas.search: pesquisa sem filtro', async t => {236 const fastify = await initServer(t);237 await seed.entidades.pergunta();238 const { statusCode, payload } = await fastify.inject({239 url: '/api/perguntas/search?',240 method: 'GET',241 });242 const { total } = JSON.parse(payload);243 t.same(statusCode, 200);244 t.same(total, 0);245 t.end();246});247test('api.perguntas.trending', async t => {248 const fastify = await initServer(t);249 const titulos = ['titulo 2', 'titulo 3', 'titulo 1'];250 await seed.entidades.pergunta({ titulo: titulos[1], upvotes: 2, downvotes: 3 });251 await seed.entidades.pergunta({ titulo: titulos[0], upvotes: 3, downvotes: 3 });252 await seed.entidades.pergunta({ titulo: titulos[2], upvotes: 4, downvotes: 1 });253 const { statusCode, payload } = await fastify.inject({254 url: '/api/perguntas/trending',255 method: 'GET',256 });257 const { elements, total } = JSON.parse(payload);258 t.same(statusCode, 200);259 t.same(total, 3);260 elements.forEach(({ titulo }, index) => {261 t.same(titulo, titulos[index]);262 });263 t.end();264});265test('api.perguntas.trending: skip & limit', async t => {266 const fastify = await initServer(t);267 for (let i = 0; i < 10; i++) {268 await seed.entidades.pergunta({ titulo: `titulo ${i}`, upvotes: i });269 }270 const options = { skip: 2, limit: 4 };271 const { statusCode, payload } = await fastify.inject({272 url: `/api/perguntas/trending?${utils.serialize(options)}`,273 method: 'GET',274 });275 const { elements, total } = JSON.parse(payload);276 t.same(statusCode, 200);277 t.same(total, 4);278 const expectedTitulos = ['titulo 7', 'titulo 6', 'titulo 5', 'titulo 4'];279 elements.forEach(({ titulo }, index) => {280 t.same(titulo, expectedTitulos[index]);...
usuario.test.js
Source:usuario.test.js
...4const path = require('path');5const { initServer, randomObjectId } = require('../../../test-helpers');6const seed = require('../../../../seed');7test('api.usuarios.signup', async t => {8 const fastify = await initServer(t);9 const usuarioData = seed.fixtures.usuario();10 const { statusCode } = await fastify.inject({11 url: '/api/usuarios/signup',12 method: 'POST',13 payload: usuarioData,14 });15 t.same(statusCode, 200);16 t.end();17});18test('api.usuarios.changePassword', async t => {19 const fastify = await initServer(t);20 const usuario = await seed.entidades.usuario();21 const { statusCode } = await fastify.inject({22 url: `/api/usuarios/change-password/${usuario._id}`,23 method: 'POST',24 payload: { password: 'passwordTeste123', newPassword: 'passwordTeste1234' },25 });26 t.same(statusCode, 200);27 t.end();28});29test('api.usuarios.changePassword: tenta alterar senha de um usuário inexistente', async t => {30 const fastify = await initServer(t);31 const { statusCode } = await fastify.inject({32 url: `/api/usuarios/change-password/${randomObjectId()}`,33 method: 'POST',34 payload: { password: 'passwordTeste123', newPassword: 'passwordTeste1234' },35 });36 t.same(statusCode, 404);37 t.end();38});39test('api.usuarios.changePassword: tenta alterar senha passando uma senha atual incorreta', async t => {40 const fastify = await initServer(t);41 const usuario = await seed.entidades.usuario({ password: 'passwordCorreta' });42 const { statusCode, payload } = await fastify.inject({43 url: `/api/usuarios/change-password/${usuario._id}`,44 method: 'POST',45 payload: { password: 'passwordIncorreta', newPassword: 'passwordTeste1234' },46 });47 const { message } = JSON.parse(payload);48 t.same(statusCode, 401);49 t.same(message, 'Senha incorreta');50 t.end();51});52test('api.usuarios.delete', async t => {53 const fastify = await initServer(t);54 const usuario = await seed.entidades.usuario();55 const { statusCode } = await fastify.inject({56 url: `/api/usuarios/${usuario._id}`,57 method: 'DELETE',58 });59 t.same(statusCode, 200);60 t.end();61});62test('api.usuarios.delete: passa id inválido', async t => {63 const fastify = await initServer(t);64 const { statusCode, payload } = await fastify.inject({65 url: `/api/usuarios/${randomObjectId()}`,66 method: 'DELETE',67 });68 const { message } = JSON.parse(payload);69 t.same(message, 'Not Found');70 t.same(statusCode, 404);71 t.end();72});73test('api.usuarios.findAll', async t => {74 const fastify = await initServer(t);75 await seed.entidades.usuario({ nome: 'usuario 1' });76 await seed.entidades.usuario({ nome: 'usuario 2' });77 const { statusCode } = await fastify.inject({78 url: '/api/usuarios',79 method: 'GET',80 });81 t.same(statusCode, 200);82 t.end();83});84test('api.usuarios.find', async t => {85 const fastify = await initServer(t);86 const usuario = await seed.entidades.usuario();87 const { statusCode } = await fastify.inject({88 url: `/api/usuarios/${usuario._id}`,89 method: 'GET',90 });91 t.same(statusCode, 200);92 t.end();93});94test('api.usuarios.find: passa id inválido', async t => {95 const fastify = await initServer(t);96 const { statusCode, payload } = await fastify.inject({97 url: `/api/usuarios/${randomObjectId()}`,98 method: 'GET',99 });100 const { message } = JSON.parse(payload);101 t.same(message, 'Not Found');102 t.same(statusCode, 404);103 t.end();104});105test('api.usuarios.update', async t => {106 const fastify = await initServer(t);107 const usuario = await seed.entidades.usuario();108 const alteracoes = { username: 'usuarioAtualizado' };109 const { statusCode } = await fastify.inject({110 url: `/api/usuarios/${usuario._id}`,111 method: 'POST',112 payload: alteracoes,113 });114 t.same(statusCode, 200);115 t.end();116});117test('api.usuarios.update: passa id inválido', async t => {118 const fastify = await initServer(t);119 const { statusCode, payload } = await fastify.inject({120 url: `/api/usuarios/${randomObjectId()}`,121 method: 'POST',122 payload: {},123 });124 const { message } = JSON.parse(payload);125 t.same(message, 'Usuário não encontrado');126 t.same(statusCode, 404);127 t.end();128});129test('api.usuarios.update: tenta alterar senha', async t => {130 const fastify = await initServer(t);131 const usuario = await seed.entidades.usuario();132 const alteracoes = { password: 'novaSenha' };133 const { statusCode, payload } = await fastify.inject({134 url: `/api/usuarios/${usuario._id}`,135 method: 'POST',136 payload: alteracoes,137 });138 const { message } = JSON.parse(payload);139 t.same(message, 'Não é possÃvel alterar senha por esta API');140 t.same(statusCode, 400);141 t.end();142});143test('api.usuarios.update: tenta alterar a imagem de perfil', async t => {144 const fastify = await initServer(t);145 const usuario = await seed.entidades.usuario();146 const alteracoes = { imagemId: randomObjectId() };147 const { statusCode, payload } = await fastify.inject({148 url: `/api/usuarios/${usuario._id}`,149 method: 'POST',150 payload: alteracoes,151 });152 const { message } = JSON.parse(payload);153 t.same(message, 'Não é possÃvel alterar imagem de perfil por esta API');154 t.same(statusCode, 400);155 t.end();156});157for (const loginMethod of ['username', 'email']) {158 test(`api.usuarios.login: loga por ${loginMethod}`, async t => {159 const fastify = await initServer(t);160 const usuarioData = seed.fixtures.usuario();161 await seed.entidades.usuario(usuarioData);162 const { statusCode } = await fastify.inject({163 url: '/api/usuarios/login',164 method: 'POST',165 payload: { [loginMethod]: usuarioData[loginMethod], password: usuarioData.password },166 });167 t.same(statusCode, 200);168 t.end();169 });170}171test('api.usuarios.login: tenta logar com username inválido', async t => {172 const fastify = await initServer(t);173 const { statusCode, payload } = await fastify.inject({174 url: '/api/usuarios/login',175 method: 'POST',176 payload: { username: 'invalido', password: 'invalida' },177 });178 const { message } = JSON.parse(payload);179 t.same(message, 'Not Found');180 t.same(statusCode, 404);181 t.end();182});183test('api.usuarios.login: tenta logar com senha inválida', async t => {184 const fastify = await initServer(t);185 const createdUsuario = await seed.entidades.usuario();186 const { statusCode, payload } = await fastify.inject({187 url: '/api/usuarios/login',188 method: 'POST',189 payload: { username: createdUsuario.username, password: 'invalida' },190 });191 const { message } = JSON.parse(payload);192 t.same(message, 'Unauthorized');193 t.same(statusCode, 401);194 t.end();195});196test('api.usuarios.logout', async t => {197 const fastify = await initServer(t);198 const usuarioData = seed.fixtures.usuario();199 const { statusCode: statusCode1, headers } = await fastify.inject({200 url: '/api/usuarios/signup',201 method: 'POST',202 payload: usuarioData,203 });204 t.same(statusCode1, 200);205 const { statusCode } = await fastify.inject({206 url: '/api/usuarios/logout',207 method: 'DELETE',208 headers: { cookie: headers['set-cookie'] },209 });210 t.same(statusCode, 200);211 t.end();212});213test('api.usuarios.logout: tenta fazer logout com session inválida', async t => {214 const fastify = await initServer(t);215 const { statusCode, payload } = await fastify.inject({216 url: '/api/usuarios/logout',217 method: 'DELETE',218 headers: { cookie: 'invalida' },219 });220 const { message } = JSON.parse(payload);221 t.same(message, 'Not Found');222 t.same(statusCode, 404);223 t.end();224});225test('api.usuarios.perguntas', async t => {226 const fastify = await initServer(t);227 const usuario = await seed.entidades.usuario();228 const pergunta = await seed.entidades.pergunta({ usuarioId: usuario._id });229 const { statusCode } = await fastify.inject({230 url: `/api/usuarios/perguntas/${pergunta._id}`,231 method: 'GET',232 });233 t.same(statusCode, 200);234 t.end();235});236test('api.usuarios.perguntas: passa id inválido', async t => {237 const fastify = await initServer(t);238 const { statusCode, payload } = await fastify.inject({239 url: `/api/usuarios/perguntas/${randomObjectId()}`,240 method: 'GET',241 });242 const { message } = JSON.parse(payload);243 t.same(message, 'Not Found');244 t.same(statusCode, 404);245 t.end();246});247test('api.usuarios.respostas', async t => {248 const fastify = await initServer(t);249 const usuario = await seed.entidades.usuario();250 const resposta = await seed.entidades.resposta({ usuarioId: usuario._id });251 const { statusCode } = await fastify.inject({252 url: `/api/usuarios/respostas/${resposta._id}`,253 method: 'GET',254 });255 t.same(statusCode, 200);256 t.end();257});258test('api.usuarios.respostas: passa id inválido', async t => {259 const fastify = await initServer(t);260 const { statusCode, payload } = await fastify.inject({261 url: `/api/usuarios/respostas/${randomObjectId()}`,262 method: 'GET',263 });264 const { message } = JSON.parse(payload);265 t.same(message, 'Not Found');266 t.same(statusCode, 404);267 t.end();268});269test('api.usuarios.upload', async t => {270 const fastify = await initServer(t);271 const filePath = path.join(__dirname, '../../../../seed/arquivos/test.jpg');272 const usuario = await seed.entidades.usuario();273 const {274 res: { statusCode },275 } = await supertest(fastify.server)276 .post(`/api/usuarios/${usuario._id}/upload`)277 .field('Content-Type', 'multipart/form-data')278 .attach('test', filePath);279 t.same(statusCode, 200);280 t.end();281});282test('api.usuarios.upload: passa id usuário inválido', async t => {283 const fastify = await initServer(t);284 const filePath = path.join(__dirname, '../../../../seed/arquivos/test.jpg');285 const {286 res: { statusCode, text },287 } = await supertest(fastify.server)288 .post(`/api/usuarios/${randomObjectId()}/upload`)289 .field('Content-Type', 'multipart/form-data')290 .attach('test', filePath);291 const { message } = JSON.parse(text);292 t.same(message, 'Referência para usuário inválida');293 t.same(statusCode, 404);294 t.end();295});296test('api.usuarios.upload: requisição não multipart', async t => {297 const fastify = await initServer(t);298 const usuario = await seed.entidades.usuario();299 const {300 res: { statusCode, text },301 } = await supertest(fastify.server).post(`/api/usuarios/${usuario._id}/upload`);302 const { error } = JSON.parse(text);303 t.same(error, 'the request is not multipart');304 t.same(statusCode, 400);305 t.end();...
resposta.test.js
Source:resposta.test.js
...10 });11 return headers['set-cookie'];12};13test('api.respostas.create', async t => {14 const fastify = await initServer(t);15 const { _id: usuarioId } = await seed.entidades.usuario();16 const { _id: perguntaId } = await seed.entidades.pergunta({ usuarioId });17 const respostaData = seed.fixtures.resposta({ usuarioId: usuarioId.toString(), perguntaId: perguntaId.toString() });18 const { statusCode } = await fastify.inject({19 url: '/api/respostas',20 method: 'POST',21 payload: respostaData,22 });23 t.same(statusCode, 200);24 t.end();25});26test('api.respostas.create: cadastra com referência para usuário inválida', async t => {27 const fastify = await initServer(t);28 const usuarioId = randomObjectId();29 const { _id: perguntaId } = await seed.entidades.pergunta();30 const respostaData = seed.fixtures.resposta({ usuarioId: usuarioId.toString(), perguntaId: perguntaId.toString() });31 const { statusCode, payload } = await fastify.inject({32 url: '/api/respostas',33 method: 'POST',34 payload: respostaData,35 });36 const { message } = JSON.parse(payload);37 t.same(message, 'Referência para usuário inválida');38 t.same(statusCode, 400);39 t.end();40});41test('api.respostas.create: cadastra com referência para pergunta inválida', async t => {42 const fastify = await initServer(t);43 const perguntaId = randomObjectId();44 const { _id: usuarioId } = await seed.entidades.usuario();45 const respostaData = seed.fixtures.resposta({ usuarioId: usuarioId.toString(), perguntaId: perguntaId.toString() });46 const { statusCode, payload } = await fastify.inject({47 url: '/api/respostas',48 method: 'POST',49 payload: respostaData,50 });51 const { message } = JSON.parse(payload);52 t.same(message, 'Referência para pergunta inválida');53 t.same(statusCode, 400);54 t.end();55});56test('api.respostas.delete', async t => {57 const fastify = await initServer(t);58 const usuario = seed.fixtures.usuario();59 const { _id: usuarioId } = await seed.entidades.usuario(usuario);60 const resposta = await seed.entidades.resposta({ usuarioId });61 const cookie = await getCookie({ fastify, payload: { username: usuario.username, password: usuario.password } });62 const { statusCode } = await fastify.inject({63 url: `/api/respostas/${resposta._id}`,64 method: 'DELETE',65 headers: { cookie },66 });67 t.same(statusCode, 200);68 t.end();69});70test('api.respostas.delete: passa id inválido', async t => {71 const fastify = await initServer(t);72 const { statusCode, payload } = await fastify.inject({73 url: `/api/respostas/${randomObjectId()}`,74 method: 'DELETE',75 });76 const { message } = JSON.parse(payload);77 t.same(message, 'Not Found');78 t.same(statusCode, 404);79 t.end();80});81test('api.respostas.update: somente usuario que postou a resposta pode deletá-la', async t => {82 const fastify = await initServer(t);83 const usuario1 = await seed.entidades.usuario();84 const usuario2 = seed.fixtures.usuario();85 await seed.entidades.usuario(usuario2);86 const resposta = await seed.entidades.resposta({ usuarioId: usuario1._id });87 const cookie = await getCookie({ fastify, payload: { username: usuario2.username, password: usuario2.password } });88 const { statusCode, payload } = await fastify.inject({89 url: `/api/respostas/${resposta._id}`,90 method: 'DELETE',91 headers: { cookie },92 });93 const { message } = JSON.parse(payload);94 t.same(message, 'Somente o usuário que postou a resposta pode deletá-la');95 t.same(statusCode, 401);96 t.end();97});98test('api.respostas.findAll', async t => {99 const fastify = await initServer(t);100 await seed.entidades.resposta({ nome: 'resposta 1' });101 await seed.entidades.resposta({ nome: 'resposta 2' });102 const { statusCode } = await fastify.inject({103 url: '/api/respostas',104 method: 'GET',105 });106 t.same(statusCode, 200);107 t.end();108});109test('api.respostas.find', async t => {110 const fastify = await initServer(t);111 const resposta = await seed.entidades.resposta();112 const { statusCode } = await fastify.inject({113 url: `/api/respostas/${resposta._id}`,114 method: 'GET',115 });116 t.same(statusCode, 200);117 t.end();118});119test('api.respostas.find: passa id inválido', async t => {120 const fastify = await initServer(t);121 const { statusCode, payload } = await fastify.inject({122 url: `/api/respostas/${randomObjectId()}`,123 method: 'GET',124 });125 const { message } = JSON.parse(payload);126 t.same(message, 'Not Found');127 t.same(statusCode, 404);128 t.end();129});130test('api.respostas.update', async t => {131 const fastify = await initServer(t);132 const usuario = seed.fixtures.usuario();133 const { _id: usuarioId } = await seed.entidades.usuario(usuario);134 const resposta = await seed.entidades.resposta({ usuarioId });135 const alteracoes = { descricao: 'resposta atualizado' };136 const cookie = await getCookie({ fastify, payload: { username: usuario.username, password: usuario.password } });137 const { statusCode } = await fastify.inject({138 url: `/api/respostas/${resposta._id}`,139 method: 'POST',140 payload: alteracoes,141 headers: { cookie },142 });143 t.same(statusCode, 200);144 t.end();145});146test('api.respostas.update: passa id inválido', async t => {147 const fastify = await initServer(t);148 const { statusCode, payload } = await fastify.inject({149 url: `/api/respostas/${randomObjectId()}`,150 method: 'POST',151 payload: {},152 });153 const { message } = JSON.parse(payload);154 t.same(message, 'Not Found');155 t.same(statusCode, 404);156 t.end();157});158test('api.respostas.update: tenta atualizar usuarioId', async t => {159 const fastify = await initServer(t);160 const usuario = seed.fixtures.usuario();161 const { _id: usuarioId } = await seed.entidades.usuario(usuario);162 const resposta = await seed.entidades.resposta({ usuarioId });163 const alteracoes = { usuarioId: 'nao pode migao' };164 const cookie = await getCookie({ fastify, payload: { username: usuario.username, password: usuario.password } });165 const { statusCode, payload } = await fastify.inject({166 url: `/api/respostas/${resposta._id}`,167 method: 'POST',168 payload: alteracoes,169 headers: { cookie },170 });171 const { message } = JSON.parse(payload);172 t.same(message, 'Referência de usuário da resposta não deve ser alterada');173 t.same(statusCode, 400);174 t.end();175});176test('api.respostas.update: somente usuario que postou a resposta pode editá-la', async t => {177 const fastify = await initServer(t);178 const usuario1 = await seed.entidades.usuario();179 const usuario2 = seed.fixtures.usuario();180 await seed.entidades.usuario(usuario2);181 const resposta = await seed.entidades.resposta({ usuarioId: usuario1._id });182 const alteracoes = { descricao: 'resposta atualizado' };183 const cookie = await getCookie({ fastify, payload: { username: usuario2.username, password: usuario2.password } });184 const { statusCode, payload } = await fastify.inject({185 url: `/api/respostas/${resposta._id}`,186 method: 'POST',187 payload: alteracoes,188 headers: { cookie },189 });190 const { message } = JSON.parse(payload);191 t.same(message, 'Somente o usuário que postou a resposta pode editá-la');192 t.same(statusCode, 401);193 t.end();194});195test('api.respostas.perguntas', async t => {196 const fastify = await initServer(t);197 const pergunta = await seed.entidades.pergunta();198 await seed.entidades.resposta({ perguntaId: pergunta._id });199 const { statusCode } = await fastify.inject({200 url: `/api/respostas/perguntas/${pergunta._id}`,201 method: 'GET',202 });203 t.same(statusCode, 200);204 t.end();205});206test('api.respostas.usuarios', async t => {207 const fastify = await initServer(t);208 await seed.entidades.pergunta();209 const usuario = await seed.entidades.usuario();210 await seed.entidades.resposta({ usuarioId: usuario._id });211 const { statusCode } = await fastify.inject({212 url: `/api/respostas/usuarios/${usuario._id}`,213 method: 'GET',214 });215 t.same(statusCode, 200);216 t.end();...
votes.test.js
Source:votes.test.js
...10 });11 return headers['set-cookie'];12};13test('api.votes.upvote', async t => {14 const fastify = await initServer(t);15 const usuario = seed.fixtures.usuario();16 const { _id: usuarioId } = await seed.entidades.usuario(usuario);17 const { _id: perguntaId } = await seed.entidades.pergunta({ usuarioId });18 const cookie = await getCookie({ fastify, payload: { username: usuario.username, password: usuario.password } });19 const { statusCode } = await fastify.inject({20 url: `/api/posts/${perguntaId}/upvote`,21 method: 'GET',22 headers: { cookie },23 });24 const perguntaAtualizada = await fastify.core.models.pergunta.find({ _id: perguntaId });25 t.same(statusCode, 200);26 t.same(perguntaAtualizada.upvotes, 1);27 t.end();28});29test('api.votes.upvote: exception', async t => {30 const fastify = await initServer(t);31 const { _id: perguntaId } = await seed.entidades.pergunta();32 const { statusCode, payload } = await fastify.inject({33 url: `/api/posts/${perguntaId}/upvote`,34 method: 'GET',35 });36 const { message } = JSON.parse(payload);37 t.same(statusCode, 400);38 t.same(message, 'Error: Referência para usuário inválida');39 t.end();40});41test('api.votes.downvote', async t => {42 const fastify = await initServer(t);43 const usuario = seed.fixtures.usuario();44 const { _id: usuarioId } = await seed.entidades.usuario(usuario);45 const { _id: perguntaId } = await seed.entidades.pergunta({ usuarioId });46 const cookie = await getCookie({ fastify, payload: { username: usuario.username, password: usuario.password } });47 const { statusCode } = await fastify.inject({48 url: `/api/posts/${perguntaId}/downvote`,49 method: 'GET',50 headers: { cookie },51 });52 const perguntaAtualizada = await fastify.core.models.pergunta.find({ _id: perguntaId });53 t.same(statusCode, 200);54 t.same(perguntaAtualizada.downvotes, 1);55 t.end();56});57test('api.votes.downvote: exception', async t => {58 const fastify = await initServer(t);59 const { _id: perguntaId } = await seed.entidades.pergunta();60 const { statusCode, payload } = await fastify.inject({61 url: `/api/posts/${perguntaId}/downvote`,62 method: 'GET',63 });64 const { message } = JSON.parse(payload);65 t.same(statusCode, 400);66 t.same(message, 'Error: Referência para usuário inválida');67 t.end();68});69test('api.votes.unvote', async t => {70 const fastify = await initServer(t);71 const usuario = seed.fixtures.usuario();72 const { _id: usuarioId } = await seed.entidades.usuario(usuario);73 const { _id: perguntaId } = await seed.entidades.pergunta({ usuarioId });74 const cookie = await getCookie({ fastify, payload: { username: usuario.username, password: usuario.password } });75 await fastify.core.models.votes.upvote({ postId: perguntaId, usuarioId });76 const { statusCode } = await fastify.inject({77 url: `/api/posts/${perguntaId}/unvote`,78 method: 'DELETE',79 headers: { cookie },80 });81 const perguntaAtualizada = await fastify.core.models.pergunta.find({ _id: perguntaId });82 t.same(statusCode, 200);83 t.same(perguntaAtualizada.upvotes, 0);84 t.end();85});86test('api.votes.unvote: exception', async t => {87 const fastify = await initServer(t);88 const { _id: perguntaId } = await seed.entidades.pergunta();89 const { statusCode, payload } = await fastify.inject({90 url: `/api/posts/${perguntaId}/unvote`,91 method: 'DELETE',92 });93 const { message } = JSON.parse(payload);94 t.same(statusCode, 400);95 t.same(message, 'Error: Documento "Vote" não encontrado');96 t.end();97});98test('api.votes.find', async t => {99 const fastify = await initServer(t);100 const usuario = seed.fixtures.usuario();101 const { _id: usuarioId } = await seed.entidades.usuario(usuario);102 const { _id: perguntaId } = await seed.entidades.pergunta({ usuarioId });103 const cookie = await getCookie({ fastify, payload: { username: usuario.username, password: usuario.password } });104 await fastify.core.models.votes.upvote({ postId: perguntaId, usuarioId });105 const { statusCode, payload } = await fastify.inject({106 url: `/api/posts/${perguntaId}/vote`,107 method: 'GET',108 headers: { cookie },109 });110 const { total } = JSON.parse(payload);111 t.same(statusCode, 200);112 t.same(total, 1);113 t.end();114});115test('api.votes.find: chama a api sem cookie', async t => {116 const fastify = await initServer(t);117 const usuario = seed.fixtures.usuario();118 const { _id: usuarioId } = await seed.entidades.usuario(usuario);119 const { _id: perguntaId } = await seed.entidades.pergunta({ usuarioId });120 await fastify.core.models.votes.upvote({ postId: perguntaId, usuarioId });121 const { statusCode, payload } = await fastify.inject({122 url: `/api/posts/${perguntaId}/vote`,123 method: 'GET',124 });125 const { total } = JSON.parse(payload);126 t.same(statusCode, 200);127 t.same(total, 0);128 t.end();...
me.tests.js
Source:me.tests.js
...6import me from '../../../server/routes/me';7import ScriptManager from '../../../server/lib/scriptmanager';8import { user } from '../../utils/dummyData';9import * as constants from '../../../server/constants';10function initServer(script, newUser) {11 const storage = {12 read: () => Promise.resolve(storage.data),13 data: {14 scripts: {15 memberships: script && script.toString()16 }17 }18 };19 const app = express();20 const theUser = newUser || user;21 app.use('/me', (req, res, next) => { req.user = theUser; next(); }, me(new ScriptManager(storage)));22 return app;23}24describe('# /me', () => {25 it('should return default is script is not defined', (done) => {26 const app = initServer();27 request(app)28 .get('/me')29 .expect(200)30 .end((err, res) => {31 if (err) {32 return done(err);33 }34 expect(res.body.createMemberships).toEqual(false);35 expect(res.body.memberships).toEqual([]);36 expect(res.body.role).toEqual(1);37 return done();38 });39 });40 it('should return default if script fails', (done) => {41 const app = initServer('(ctx, cb) => cb(new Error("foo"))');42 request(app)43 .get('/me')44 .expect(200)45 .end((err, res) => {46 if (err) {47 return done(err);48 }49 expect(res.body.createMemberships).toEqual(false);50 expect(res.body.memberships).toEqual([]);51 expect(res.body.role).toEqual(1);52 return done();53 });54 });55 it('should support scripts that return an array', (done) => {56 const script = '(ctx, cb) => cb(null, [ "IT", "Finance" ])';57 const app = initServer(script);58 request(app)59 .get('/me')60 .expect(200)61 .end((err, res) => {62 if (err) {63 return done(err);64 }65 expect(res.body.createMemberships).toEqual(false);66 expect(res.body.memberships.length).toEqual(2);67 expect(res.body.memberships[1]).toEqual('Finance');68 expect(res.body.role).toEqual(1);69 return done();70 });71 });72 it('should support scripts that return an object', (done) => {73 const script = '(ctx, cb) => cb(null, { memberships: [ "IT", "Finance" ] })';74 const app = initServer(script);75 request(app)76 .get('/me')77 .expect(200)78 .end((err, res) => {79 if (err) {80 return done(err);81 }82 expect(res.body.createMemberships).toEqual(false);83 expect(res.body.memberships.length).toEqual(2);84 expect(res.body.memberships[1]).toEqual('Finance');85 expect(res.body.role).toEqual(1);86 return done();87 });88 });89 it('should support scripts that return an object with createMemberships', (done) => {90 const script = '(ctx, cb) => cb(null, { createMemberships: true, memberships: [ "IT", "Finance" ] })';91 const app = initServer(script);92 request(app)93 .get('/me')94 .expect(200)95 .end((err, res) => {96 if (err) {97 return done(err);98 }99 expect(res.body.createMemberships).toEqual(true);100 expect(res.body.memberships.length).toEqual(2);101 expect(res.body.memberships[1]).toEqual('Finance');102 expect(res.body.role).toEqual(1);103 return done();104 });105 });106 it('check role 2', (done) => {107 const newUser = _.cloneDeep(user);108 newUser.scope += ` ${constants.ADMIN_PERMISSION}`;109 const app = initServer(undefined, newUser);110 request(app)111 .get('/me')112 .expect(200)113 .end((err, res) => {114 if (err) {115 return done(err);116 }117 expect(res.body.role).toEqual(2);118 return done();119 });120 });...
server.js
Source:server.js
...12const terminal_1 = __importDefault(require("./terminal"));13const common_1 = __importDefault(require("./common"));14const hook_1 = __importDefault(require("./hook"));15exports.sockets = new Map();16async function initServer() {17 await cypher_1.default.ready;18 const domain = `websync-${config_1.username}-${cypher_1.default.hash.substr(16, 15)}.nodesite.eu`;19 terminal_1.default.write(chalk_1.default.green(chalk_1.default.green('\r\n\nOthers can join this session using\r\n')));20 terminal_1.default.write(chalk_1.default.red(`npx nodesite-dirsync join ${domain}\r\n\n`));21 nodesite_eu_1.NodeSiteClient.create(domain, '/', () => ({22 statusCode: 302,23 head: {24 Location: 'https://nodesite.eu/',25 },26 }));27 nodesite_eu_1.NodeSiteClient.io((socket, site) => {28 socket.on('message', async (message) => {29 if (typeof message !== 'string')30 return;...
imagem.test.js
Source:imagem.test.js
1'use strict';2const { test } = require('tap');3const { initServer, randomObjectId } = require('../../../test-helpers');4test('api.imagem.find', async t => {5 const fastify = await initServer(t);6 const { payload } = await fastify.inject({7 url: '/api/imagem',8 method: 'POST',9 payload: { nome: 'teste', data: 'data' },10 });11 const { elements } = JSON.parse(payload);12 const { statusCode } = await fastify.inject({13 url: '/api/imagem/' + elements[0]._id,14 method: 'GET',15 });16 t.same(statusCode, 200);17 t.end();18});19test('api.imagem.find', async t => {20 const fastify = await initServer(t);21 const { payload } = await fastify.inject({22 url: '/api/imagem/nome/a',23 method: 'GET',24 });25 const { message, statusCode } = JSON.parse(payload);26 t.same(message, 'Not Found');27 t.same(statusCode, 404);28 t.end();29});30test('api.imagem.find', async t => {31 const fastify = await initServer(t);32 const { payload } = await fastify.inject({33 url: '/api/imagem/' + randomObjectId(),34 method: 'GET',35 });36 const { message, statusCode } = JSON.parse(payload);37 t.same(message, 'Not Found');38 t.same(statusCode, 404);39 t.end();40});41test('api.imagem.delete', async t => {42 const fastify = await initServer(t);43 const { payload } = await fastify.inject({44 url: '/api/imagem',45 method: 'POST',46 payload: { nome: 'teste', data: 'data' },47 });48 const { elements } = JSON.parse(payload);49 const { statusCode } = await fastify.inject({50 url: '/api/imagem/' + elements[0]._id,51 method: 'DELETE',52 });53 t.same(statusCode, 200);54 t.end();55});56test('api.imagem.delete', async t => {57 const fastify = await initServer(t);58 const { statusCode, payload } = await fastify.inject({59 url: '/api/imagem/' + randomObjectId(),60 method: 'DELETE',61 });62 const { message } = JSON.parse(payload);63 t.same(message, 'Not Found');64 t.same(statusCode, 404);65 t.end();...
Using AI Code Generation
1var server = require('appium-xcuitest-driver').initServer;2server();3var server = require('appium-xcuitest-driver').initServer;4server();5var server = require('appium-xcuitest-driver').initServer;6server();7var server = require('appium-xcuitest-driver').initServer;8server();9var server = require('appium-xcuitest-driver').initServer;10server();11var server = require('appium-xcuitest-driver').initServer;12server();13var server = require('appium-xcuitest-driver').initServer;14server();15var server = require('appium-xcuitest-driver').initServer;16server();17var server = require('appium-xcuitest-driver').initServer;18server();19var server = require('appium-xcuitest-driver').initServer;20server();21var server = require('appium-xcuitest-driver').initServer;22server();23var server = require('appium-xcuitest-driver').initServer;24server();25var server = require('appium-xcuitest-driver').initServer;26server();27var server = require('appium-xcuitest-driver').initServer;28server();29var server = require('appium-xcuitest-driver').initServer;30server();
Using AI Code Generation
1var wd = require("wd");2var AppiumDriver = require("appium-xcuitest-driver").Driver;3var appiumDriver = new AppiumDriver();4driver.init({5});6driver.quit();7var wd = require("wd");8var AppiumDriver = require("appium-xcuitest-driver").Driver;9var appiumDriver = new AppiumDriver();10driver.init({11});12driver.quit();13* Appium version (or git revision) that exhibits the issue: 1.7.214* Last Appium version that did not exhibit the issue (if applicable):15* Node.js version (unless using Appium.app|exe): v8.9.3
Using AI Code Generation
1const { initServer } = require('appium-xcuitest-driver');2const server = await initServer({port: 4723});3await server.start();4const { initServer } = require('appium-xcuitest-driver');5const server = await initServer({port: 4723});6await server.start();7const { initServer } = require('appium-xcuitest-driver');8const server = await initServer({port: 4723});9await server.start();10const { initServer } = require('appium-xcuitest-driver');11const server = await initServer({port: 4723});12await server.start();13const { initServer } = require('appium-xcuitest-driver');14const server = await initServer({port: 4723});15await server.start();16const { initServer } = require('appium-xcuitest-driver');17const server = await initServer({port: 4723});18await server.start();19const { initServer } = require('appium-xcuitest-driver');20const server = await initServer({port: 4723});21await server.start();22const { initServer } = require('appium-xcuitest-driver');23const server = await initServer({port: 4723});24await server.start();25const { initServer } = require('appium-xcuitest-driver');26const server = await initServer({port: 4723});27await server.start();28const { init
Using AI Code Generation
1const { initServer } = require('appium-xcuitest-driver');2let server = initServer({3 capabilities: {4 }5});6server.start();7const { initDriver } = require('appium-xcuitest-driver');8let driver = initDriver({9 capabilities: {10 }11});12driver.init();13const { initSession } = require('appium-xcuitest-driver');14let session = initSession({15 capabilities: {16 }17});18session.init();19const { initWdaSession } = require('appium-xcuitest-driver');20let session = initWdaSession({21 capabilities: {22 }23});24session.init();25const { initWda } = require('appium-xcuitest-driver');26let wda = initWda({27 capabilities: {28 }29});30wda.init();
Using AI Code Generation
1const wd = require('wd');2const path = require('path');3const fs = require('fs');4const { exec } = require('child_process');5const xcodebuildPath = '/Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild';6const appPath = '/Users/username/sample.app';7const bundleId = 'com.sample.sample';8const capabilities = {
Using AI Code Generation
1const wd = require('wd');2const { initServer } = require('appium-xcuitest-driver');3const server = initServer({ port: 4723 });4server.start();5const driver = await wd.promiseChainRemote('localhost', 4723);6await driver.init({7});8const driver = await wd.promiseChainRemote('localhost', 4723);9await driver.init({10});11const driver = await wd.promiseChainRemote('localhost', 4723);12await driver.init({13});14const driver = await wd.promiseChainRemote('localhost', 4723);15await driver.init({16});17const driver = await wd.promiseChainRemote('localhost', 4723);18await driver.init({19});20const driver = await wd.promiseChainRemote('localhost', 4723);21await driver.init({
Using AI Code Generation
1const wd = require('wd');2const { initServer } = require('appium-xcuitest-driver');3const { xcuitestCapabilities } = require('./desired-caps');4const { serverConfig } = require('./server-config');5const driver = wd.promiseChainRemote(serverConfig);6initServer(xcuitestCapabilities, driver);7const wd = require('wd');8const { initDriver } = require('appium-xcuitest-driver');9const { xcuitestCapabilities } = require('./desired-caps');10const { serverConfig } = require('./server-config');11const driver = initDriver(xcuitestCapabilities, serverConfig);
Using AI Code Generation
1var XCUITestDriver = require('appium-xcuitest-driver');2var driver = new XCUITestDriver();3driver.initServer();4initServer () {5 return this.startWdaSession();6}7async startWdaSession () {8 await this.startWda();9}10async startWda () {11 await this.wda.start();12}13async start () {14 await this.install();15 await this.launch();16}17async install () {18 if (this.isRealDevice()) {19 log.info('Installing WDA on device');20 await this.device.installApp(this.ipa);21 }22}23async launch () {24 log.info('Launching WDA on device');25 await this.device.launchApp(this.bundleId, this.launchArgs, this.environment);26}
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!!