Best JavaScript code snippet using argos
github-client.test.js
Source:github-client.test.js
1'use strict';2const assert = require('proclaim');3const mockery = require('mockery');4const sinon = require('sinon');5describe('lib/github-client', () => {6 let GitHubApiClient;7 let GitHubClient;8 beforeEach(() => {9 GitHubApiClient = require('../mock/octokit-rest.mock');10 mockery.registerMock('@octokit/rest', GitHubApiClient);11 GitHubClient = require('../../../lib/github-client');12 });13 it('exports a class constructor', () => {14 assert.isFunction(GitHubClient);15 assert.throws(() => GitHubClient(), /constructor githubclient/i); // eslint-disable-line new-cap16 });17 describe('new GitHubClient(githubAuthToken)', () => {18 let instance;19 beforeEach(() => {20 instance = new GitHubClient('mock-auth-token');21 });22 it('has a `client` property set to a new authenticated GitHub API client', () => {23 assert.calledOnce(GitHubApiClient);24 assert.calledWithNew(GitHubApiClient);25 assert.calledWithExactly(GitHubApiClient, {26 auth: 'mock-auth-token'27 });28 assert.strictEqual(instance.client, GitHubApiClient.mockGitHubApiClient);29 });30 describe('.extractRepoFromUrl(url)', () => {31 it('extracts the owner and repo names from a GitHub URL', () => {32 assert.deepEqual(instance.extractRepoFromUrl('https://github.com/mock-owner-1/mock-repo-1'), {33 owner: 'mock-owner-1',34 repo: 'mock-repo-1'35 });36 assert.deepEqual(instance.extractRepoFromUrl('http://www.github.com/mock-owner-2/mock-repo-2'), {37 owner: 'mock-owner-2',38 repo: 'mock-repo-2'39 });40 assert.deepEqual(instance.extractRepoFromUrl('https://github.com/mock-owner-3/mock-repo-3/issues'), {41 owner: 'mock-owner-3',42 repo: 'mock-repo-3'43 });44 });45 });46 describe('.isValidUrl(url)', () => {47 it('returns `true` if `url` is valid', () => {48 assert.isTrue(instance.isValidUrl('https://github.com/mock-owner-1/mock-repo-1'));49 assert.isTrue(instance.isValidUrl('http://www.github.com/mock-owner-2/mock-repo-2'));50 assert.isTrue(instance.isValidUrl('https://github.com/mock-owner-3/mock-repo-3/issues'));51 });52 it('returns `false` if `url` is invalid', () => {53 assert.isFalse(instance.isValidUrl('https://www.google.com'));54 assert.isFalse(instance.isValidUrl('https://github.com/mock-owner-4'));55 assert.isFalse(instance.isValidUrl('git@github.com:mock-owner-5/mock-repo-5.git'));56 });57 });58 describe('.isValidRepoAndTag(options)', () => {59 let returnValue;60 beforeEach(async () => {61 instance.client.gitdata.getRef.resolves();62 returnValue = await instance.isValidRepoAndTag({63 owner: 'mock-owner',64 repo: 'mock-repo',65 tag: 'mock-tag'66 });67 });68 it('makes a GitHub API call', () => {69 assert.calledOnce(instance.client.gitdata.getRef);70 assert.calledWithExactly(instance.client.gitdata.getRef, {71 owner: 'mock-owner',72 repo: 'mock-repo',73 ref: 'tags/mock-tag'74 });75 });76 it('resolves with `true`', () => {77 assert.isTrue(returnValue);78 });79 describe('when the repo/tag combination is not valid', () => {80 let githubError;81 beforeEach(async () => {82 githubError = new Error('mock error');83 githubError.status = 404;84 instance.client.gitdata.getRef.rejects(githubError);85 returnValue = await instance.isValidRepoAndTag({86 owner: 'mock-owner',87 repo: 'mock-repo',88 tag: 'mock-tag'89 });90 });91 it('resolves with `false`', () => {92 assert.isFalse(returnValue);93 });94 });95 describe('when the GitHub API errors', () => {96 let caughtError;97 let githubError;98 beforeEach(async () => {99 githubError = new Error('mock error');100 instance.client.gitdata.getRef.rejects(githubError);101 try {102 await instance.isValidRepoAndTag({103 owner: 'mock-owner',104 repo: 'mock-repo',105 tag: 'mock-tag'106 });107 } catch (error) {108 caughtError = error;109 }110 });111 it('rejects with the error', () => {112 assert.strictEqual(caughtError, githubError);113 });114 });115 });116 describe('.loadReadme(options)', () => {117 let returnValue;118 beforeEach(async () => {119 instance.client.repos.getReadme.resolves({120 data: {121 content: new Buffer('mock-readme-content').toString('base64')122 }123 });124 returnValue = await instance.loadReadme('mock-options');125 });126 it('makes a GitHub API call', () => {127 assert.calledOnce(instance.client.repos.getReadme);128 assert.calledWithExactly(instance.client.repos.getReadme, 'mock-options');129 });130 it('resolves with the decoded README contents', () => {131 assert.strictEqual(returnValue, 'mock-readme-content');132 });133 describe('when the repo does not have a README', () => {134 let githubError;135 beforeEach(async () => {136 githubError = new Error('mock error');137 githubError.status = 404;138 instance.client.repos.getReadme.rejects(githubError);139 returnValue = await instance.loadReadme('mock-options');140 });141 it('resolves with `null`', () => {142 assert.isNull(returnValue);143 });144 });145 describe('when the GitHub API errors', () => {146 let caughtError;147 let githubError;148 beforeEach(async () => {149 githubError = new Error('mock error');150 instance.client.repos.getReadme.rejects(githubError);151 try {152 await instance.loadReadme('mock-options');153 } catch (error) {154 caughtError = error;155 }156 });157 it('rejects with the error', () => {158 assert.strictEqual(caughtError, githubError);159 });160 });161 });162 describe('.loadFile(options)', () => {163 let returnValue;164 beforeEach(async () => {165 instance.client.repos.getContents.resolves({166 data: {167 content: new Buffer('mock-file-content').toString('base64')168 }169 });170 returnValue = await instance.loadFile('mock-options');171 });172 it('makes a GitHub API call', () => {173 assert.calledOnce(instance.client.repos.getContents);174 assert.calledWithExactly(instance.client.repos.getContents, 'mock-options');175 });176 it('resolves with the decoded file contents', () => {177 assert.strictEqual(returnValue, 'mock-file-content');178 });179 describe('when the repo does not have the requested file', () => {180 let githubError;181 beforeEach(async () => {182 githubError = new Error('mock error');183 githubError.status = 404;184 instance.client.repos.getContents.rejects(githubError);185 returnValue = await instance.loadFile('mock-options');186 });187 it('resolves with `null`', () => {188 assert.isNull(returnValue);189 });190 });191 describe('when the GitHub API errors', () => {192 let caughtError;193 let githubError;194 beforeEach(async () => {195 githubError = new Error('mock error');196 instance.client.repos.getContents.rejects(githubError);197 try {198 await instance.loadFile('mock-options');199 } catch (error) {200 caughtError = error;201 }202 });203 it('rejects with the error', () => {204 assert.strictEqual(caughtError, githubError);205 });206 });207 });208 describe('.loadJsonFile(options)', () => {209 let returnValue;210 beforeEach(async () => {211 instance.loadFile = sinon.stub().resolves('{"foo": "bar"}');212 returnValue = await instance.loadJsonFile('mock-options');213 });214 it('loads the file', () => {215 assert.calledOnce(instance.loadFile);216 assert.calledWithExactly(instance.loadFile, 'mock-options');217 });218 it('resolves with the file contents parsed as JSON', () => {219 assert.deepEqual(returnValue, {220 foo: 'bar'221 });222 });223 });224 describe('.error(message, recoverable)', () => {225 let returnValue;226 beforeEach(() => {227 returnValue = instance.error('mock-message', false);228 });229 it('returns an Error instance with the given message and an `isRecoverable` property', () => {230 assert.instanceOf(returnValue, Error);231 assert.strictEqual(returnValue.message, 'mock-message');232 assert.isFalse(returnValue.isRecoverable);233 });234 describe('when `recoverable` is undefined', () => {235 beforeEach(() => {236 returnValue = instance.error('mock-message');237 });238 it('defaults the `isRecoverable` property to `true`', () => {239 assert.isTrue(returnValue.isRecoverable);240 });241 });242 });243 describe('when `githubAuthToken` is not defined', () => {244 beforeEach(() => {245 GitHubApiClient.resetHistory();246 instance = new GitHubClient();247 });248 it('does not authenticate the API client', () => {249 assert.calledOnce(GitHubApiClient);250 assert.calledWithNew(GitHubApiClient);251 assert.calledWithExactly(GitHubApiClient, {});252 });253 });254 });...
githubClient.js
Source: githubClient.js
1import LRUCache from 'lru-cache';2import { ApolloError } from 'apollo-server';3import { pick, get } from 'lodash';4const oneHour = 1000 * 60 * 60;5const HTTP_CLIENT_ERROR = Symbol();6const isNotFoundError = error =>7 get(error[HTTP_CLIENT_ERROR], 'response.status') === 404;8class GithubError extends ApolloError {9 constructor(message, properties) {10 super(message, 'GITHUB_API_FAILURE', properties);11 }12 static fromHttpClientError(error) {13 const githubError = new GithubError('GitHub API request failed', {14 response: pick(error.response, [15 'status',16 'statusText',17 'headers',18 'data',19 ]),20 });21 githubError[HTTP_CLIENT_ERROR] = error;22 return githubError;23 }24}25export class GithubRepositoryNotFoundError extends ApolloError {26 constructor(message, properties) {27 super(message, 'GITHUB_REPOSITORY_NOT_FOUND', properties);28 }29 static fromNames(ownerName, repositoryName) {30 return new GithubRepositoryNotFoundError(31 `GitHub repository ${repositoryName} owned by ${ownerName} does not exists`,32 { ownerName, repositoryName },33 );34 }35}36class GithubClient {37 constructor({ httpClient, cacheMaxAge = oneHour, clientId, clientSecret }) {38 this.clientId = clientId;39 this.clientSecret = clientSecret;40 this.httpClient = httpClient;41 this.cache = new LRUCache({ max: 100, maxAge: cacheMaxAge });42 }43 getAuth() {44 return this.clientId && this.clientSecret45 ? {46 username: this.clientId,47 password: this.clientSecret,48 }49 : undefined;50 }51 async getRequest(url, options = {}) {52 try {53 const response = await this.httpClient.get(url, {54 ...options,55 auth: this.getAuth(),56 });57 return response;58 } catch (error) {59 throw GithubError.fromHttpClientError(error);60 }61 }62 async getRequestWithCache(cacheKey, url, options) {63 const cachedPromise = this.cache.get(cacheKey);64 if (cachedPromise) {65 const { data } = await cachedPromise;66 return data;67 }68 const promise = this.getRequest(url, options);69 this.cache.set(cacheKey, promise);70 try {71 const { data } = await promise;72 return data;73 } catch (e) {74 this.cache.del(cacheKey);75 throw e;76 }77 }78 async getRepository(username, repository) {79 try {80 const data = await this.getRequestWithCache(81 `repository.${username}.${repository}`,82 `/repos/${username}/${repository}`,83 );84 return data;85 } catch (error) {86 if (isNotFoundError(error)) {87 return null;88 }89 throw error;90 }91 }92}93const createGithubClient = options => new GithubClient(options);...
Using AI Code Generation
1var argosy = require('argosy')2var pattern = require('argosy-pattern')3var service = argosy()4service.accept({role: 'math', cmd: 'sum'}, function (msg, cb) {5 if (sum > 10) {6 cb(githubError('sum-too-high', 'Sum is too high', {sum: sum}))7 } else {8 cb(null, sum)9 }10})11service.listen(8000)12var argosy = require('argosy')13var pattern = require('argosy-pattern')14var service = argosy()15service.use({role: 'math', cmd: 'sum'}, function (msg, cb) {16 cb(githubError('sum-too-high', 'Sum is too high', {sum: msg.left + msg.right}))17})18service.connect(8000)19service.act({role: 'math', cmd: 'sum', left: 1, right: 2}, function (err, result) {20})21### `pattern.jsonError(name, message, data)`22var argosy = require('argosy')23var pattern = require('argosy-pattern')24var service = argosy()25service.accept({role: 'math', cmd: 'sum'}, function (msg, cb) {26 if (sum > 10) {27 cb(jsonError('sum-too-high', 'Sum is too high', {sum: sum}))28 } else {29 cb(null, sum)30 }31})32service.listen(8000)33var argosy = require('argosy')34var pattern = require('argosy-pattern')
Using AI Code Generation
1var argosy = require('argosy')2var argosyPattern = require('argosy-pattern')3var argosyError = require('argosy-error')4var githubError = argosyError({5 'github': {6 }7})8var service = argosy()9 .accept(argosyPattern({10 }))11 .use(githubError())12 .use(function (req, cb) {13 cb(new Error('github: 404'))14 })15service.on('error', function (err) {16})
Using AI Code Generation
1module.exports = function (argosy) {2 return argosy.pattern({3 }, function (msg, respond) {4 respond(new argosy.GitHubError('test', 404))5 })6}7#### argosy.pattern(pattern, handler)
Using AI Code Generation
1var argosy = require('argosy')2var pattern = require('argosy-pattern')3var service = argosy()4service.accept({5 foo: pattern.match('foo', function (msg, respond) {6 respond(githubError('foo error'))7 })8})9service.listen(8000)10### githubError(msg, code, [err])
Using AI Code Generation
1const pattern = require('argosy-pattern')2const github = require('argosy-github')3const argosy = require('argosy')4const service = argosy({5 seneca: {6 }7})8service.use(github, {9})10service.use({11 path: '/repos/{owner}/{repo}/readme'12}, argosy.pattern({13}, function (msg, done) {14 done(null, {15 })16}))17service.act({18 path: '/repos/{owner}/{repo}/readme'19}, {20}, function (err, resp) {21 if (err) {22 if (githubError.is(err)) {23 console.log('status: ' + err.status)24 console.log('headers: ' + JSON.stringify(err.headers))25 console.log('body: ' + JSON.stringify(err.body))26 }27 }28})
Using AI Code Generation
1const argosyError = require('argosy-error')2const error = argosyError.githubError('404', 'Not Found', 'The requested resource could not be found but may be available in the future.')3console.log(error)4const argosyError = require('argosy-error')5const error = argosyError.customError('404', 'Not Found', 'The requested resource could not be found but may be available in the future.')6console.log(error)7const argosyError = require('argosy-error')8const error = argosyError.customError('404', 'Not Found', 'The requested resource could not be found but may be available in the future.', {id: 1, name: 'test'})9console.log(error)10const argosyError = require('argosy-error')11const error = argosyError.customError('404', 'Not Found', 'The requested resource could not be found but may be available in the future.', {id: 1, name: 'test'}, 'Error: 404 Not Found')12console.log(error)13const argosyError = require('argosy-error')14const error = argosyError.customError('404', 'Not Found', 'The requested resource could not be found but may be available in the future.', {id: 1, name: 'test'}, 'Error: 404 Not Found', {id: 1, name: 'test'})15console.log(error)16const argosyError = require('argosy-error')17const error = argosyError.customError('404', 'Not Found', 'The requested resource could not be
Using AI Code Generation
1var argosyError = require('argosy-error')2var githubError = argosyError('github')3var GithubError = githubError('GithubError')4var err = new GithubError('Github is down', 503)5var argosyError = require('argosy-error')6var githubError = argosyError('github')7var GithubError = githubError('GithubError')8var err = new GithubError('Github is down', 503)9var argosyError = require('argosy-error')10var githubError = argosyError('github')11var GithubError = githubError('GithubError', 503)12var err = new GithubError('Github is down')13### `argosyError = require('argosy-error')`14### `argosyError('github')`15### `argosyError('github')('GithubError')`16### `argosyError('github')('GithubError', 503)`17### `new GithubError('Github is down')`18### `new GithubError('Github is down', 503)`
Using AI Code Generation
1var argosy = require('argosy')2var service = require('argosy-service')3var githubError = require('argosy-service').githubError4var pattern = {5}6var createRepo = service(pattern, function (msg, respond) {7 respond(githubError('repo already exists', 400))8})9var argosy = argosy()10argosy.use(createRepo)11argosy.pipe(argosy()).pipe(argosy)
Check out the latest blogs from LambdaTest on this topic:
Ever since the Internet was invented, web developers have searched for the most efficient ways to display content on web browsers.
Unit and functional testing are the prime ways of verifying the JavaScript code quality. However, a host of tools are available that can also check code before or during its execution in order to test its quality and adherence to coding standards. With each tool having its unique features and advantages contributing to its testing capabilities, you can use the tool that best suits your need for performing JavaScript testing.
“Test frequently and early.” If you’ve been following my testing agenda, you’re probably sick of hearing me repeat that. However, it is making sense that if your tests detect an issue soon after it occurs, it will be easier to resolve. This is one of the guiding concepts that makes continuous integration such an effective method. I’ve encountered several teams who have a lot of automated tests but don’t use them as part of a continuous integration approach. There are frequently various reasons why the team believes these tests cannot be used with continuous integration. Perhaps the tests take too long to run, or they are not dependable enough to provide correct results on their own, necessitating human interpretation.
In an ideal world, you can test your web application in the same test environment and return the same results every time. The reality can be difficult sometimes when you have flaky tests, which may be due to the complexity of the web elements you are trying to perform an action on your test case.
Enterprise resource planning (ERP) is a form of business process management software—typically a suite of integrated applications—that assists a company in managing its operations, interpreting data, and automating various back-office processes. The introduction of a new ERP system is analogous to the introduction of a new product into the market. If the product is not handled appropriately, it will fail, resulting in significant losses for the business. Most significantly, the employees’ time, effort, and morale would suffer as a result of the procedure.
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!!