How to use TOKEN_MOCK method in ng-mocks

Best JavaScript code snippet using ng-mocks

refresh-token-unit.spec.ts

Source: refresh-token-unit.spec.ts Github

copy

Full Screen

1import faker from 'faker';2import { sign } from 'jsonwebtoken';3import auth from '@config/​auth';4import { TokenRepositoryInMemory } from '@modules/​accounts/​repositories/​in-memory';5import { DayjsFacade } from '@shared/​container/​providers/​date/​implementations';6import { JwtFacade } from '@shared/​container/​providers/​jwt/​implementations';7import { serverError, unauthorized } from '@shared/​http';8import { RefreshTokenController, RefreshTokenUseCase } from '.';9import { InvalidRefreshToken, UserTokenDoesNotExists } from './​errors';10let tokenProvider: JwtFacade;11let dateProvider: DayjsFacade;12let tokenRepository: TokenRepositoryInMemory;13let refreshTokenUseCase: RefreshTokenUseCase;14let refreshTokenController: RefreshTokenController;15const id = faker.datatype.uuid();16const token = sign({}, auth.secret_refresh_token, {17 subject: id,18});19const token_mock = {20 id: faker.datatype.uuid(),21 id_user: id,22 token,23 expires_in: faker.date.soon(),24};25const http_request = {26 body: {27 token,28 },29};30describe('refresh token: unit', () => {31 beforeAll(() => {32 tokenProvider = new JwtFacade();33 dateProvider = new DayjsFacade();34 tokenRepository = new TokenRepositoryInMemory();35 refreshTokenUseCase = new RefreshTokenUseCase(36 tokenRepository,37 dateProvider,38 tokenProvider,39 );40 refreshTokenController = new RefreshTokenController(refreshTokenUseCase);41 });42 it('should refreshTokenUseCase call your methods correctly', async () => {43 await tokenRepository.save({44 ...token_mock,45 });46 const refresh_token = 'any_refresh_token';47 const expires_in = faker.date.future();48 const verifySpy = jest.spyOn(tokenProvider, 'verify');49 const decodeSpy = jest.spyOn(tokenProvider, 'decode');50 const findByUserIdAndTokenSpy = jest.spyOn(51 tokenRepository,52 'findByUserIdAndToken',53 );54 const deleteByIdSpy = jest.spyOn(tokenRepository, 'deleteById');55 const createTokenSpy = jest56 .spyOn(tokenProvider, 'createToken')57 .mockResolvedValueOnce(refresh_token);58 const addDaysSpy = jest59 .spyOn(dateProvider, 'addDays')60 .mockReturnValueOnce(expires_in);61 const saveSpy = jest.spyOn(tokenRepository, 'save');62 await refreshTokenUseCase.execute(token);63 expect(verifySpy).toBeCalledWith(token, auth.secret_refresh_token);64 expect(decodeSpy).toBeCalledWith(token);65 expect(findByUserIdAndTokenSpy).toBeCalledWith(id, token);66 expect(deleteByIdSpy).toBeCalledWith(token_mock.id);67 expect(createTokenSpy).toBeCalledTimes(2);68 expect(addDaysSpy).toBeCalledWith(auth.expires_refresh_token_days);69 expect(saveSpy).toBeCalledWith({70 expires_in,71 id_user: id,72 token: refresh_token,73 });74 });75 it('should refreshTokenController call your methods correctly', async () => {76 const executeSpy = jest.spyOn(refreshTokenUseCase, 'execute');77 await refreshTokenController.handle(http_request);78 expect(executeSpy).toBeCalledWith(token);79 });80 it('should accept a valid refresh token', async () => {81 await tokenRepository.save({82 ...token_mock,83 });84 const http_response = await refreshTokenController.handle(http_request);85 expect(http_response.statusCode).toBe(201);86 expect(http_response.body.access_token).toBeTruthy();87 expect(http_response.body.refresh_token).toBeTruthy();88 });89 it('should not accept a invalid refresh_token', async () => {90 const token = sign({}, 'invalid_secret');91 const invalid_http_request = {92 body: {93 token,94 },95 };96 const http_response = await refreshTokenController.handle(97 invalid_http_request,98 );99 expect(http_response).toEqual(unauthorized(new InvalidRefreshToken()));100 });101 it('should not accept a not registered refresh token', async () => {102 const http_response = await refreshTokenController.handle(http_request);103 expect(http_response).toEqual(unauthorized(new UserTokenDoesNotExists()));104 });105 it('should return a server error if refreshTokenUseCase throws a error', async () => {106 jest107 .spyOn(refreshTokenUseCase, 'execute')108 .mockRejectedValueOnce(new Error());109 const http_response = await refreshTokenController.handle(http_request);110 expect(http_response).toEqual(serverError());111 });...

Full Screen

Full Screen

user.controller.test.js

Source: user.controller.test.js Github

copy

Full Screen

1'use strict'2const assert = require('chai').assert3const sinon = require('sinon')4const jwt = require('jsonwebtoken')5const { mockRequest, mockResponse } = require('mock-req-res')6const UserController = require('../​../​../​src/​controllers/​user.controller')7const TOKEN_MOCK = 'TEST-TOKEN'8describe('Test controller/​user.controller', () => {9 var req, res, next, error10 beforeEach(function (done) {11 req = mockRequest()12 req.body.username = 'test_user'13 res = mockResponse()14 next = sinon.stub()15 error = new Error('FAKE_ERROR')16 jwt.sign = sinon.stub().returns(TOKEN_MOCK)17 process.env.auth_jwtPrivateKey = '1234' /​/​ Mock jwt private key18 done()19 })20 it('should send token', async () => {21 await UserController.login(req, res, next)22 assert(res.send.calledWith(TOKEN_MOCK))23 })24 it('should call next() when error BODY_VALIDATE_ERROR', async () => {25 req.body.username = null26 await UserController.login(req, res, next)27 assert.strictEqual(next.args[0][0].message, 'BODY_VALIDATE_ERROR') /​/​ Use strictEqual and Error.message because this case throw error in try so can't mock error to use deepEqual28 assert.strictEqual(next.callCount, 1)29 })30 it('should call jwt.sign() once with object and jwtPrivatekey', async () => {31 await UserController.login(req, res, next)32 assert.strictEqual(jwt.sign.callCount, 1)33 assert.deepEqual(jwt.sign.args[0][0], { author: req.body.username })34 assert.strictEqual(jwt.sign.args[0][1], process.env.auth_jwtPrivateKey)35 })36 it('should call next() with error when error', async () => {37 jwt.sign = sinon.stub().throws(error)38 await UserController.login(req, res, next)39 assert.deepEqual(next.args[0][0], error)40 assert.strictEqual(next.callCount, 1)41 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { createToken } from 'ng-mocks';2const tokenMock = createToken('TOKEN_MOCK');3describe('TestComponent', () => {4 let component: TestComponent;5 let fixture: ComponentFixture<TestComponent>;6 beforeEach(async(() => {7 TestBed.configureTestingModule({8 {9 },10 }).compileComponents();11 }));12 beforeEach(() => {13 fixture = TestBed.createComponent(TestComponent);14 component = fixture.componentInstance;15 fixture.detectChanges();16 });17 it('should create', () => {18 expect(component).toBeTruthy();19 });20});

Full Screen

Using AI Code Generation

copy

Full Screen

1const mock = require('ng-mocks');2const mock = require('ng-mocks');3const TOKEN_MOCK = mock.TOKEN_MOCK;4const mock = require('ng-mocks');5const TOKEN_MOCK = mock.TOKEN_MOCK;6const TOKEN_MOCK = mock.TOKEN_MOCK;7const mock = require('ng-mocks');8const TOKEN_MOCK = mock.TOKEN_MOCK;9const TOKEN_MOCK = mock.TOKEN_MOCK;10const TOKEN_MOCK = mock.TOKEN_MOCK;11const mock = require('ng-moc

Full Screen

Blogs

Check out the latest blogs from LambdaTest on this topic:

How to Position Your Team for Success in Estimation

Estimates are critical if you want to be successful with projects. If you begin with a bad estimating approach, the project will almost certainly fail. To produce a much more promising estimate, direct each estimation-process issue toward a repeatable standard process. A smart approach reduces the degree of uncertainty. When dealing with presales phases, having the most precise estimation findings can assist you to deal with the project plan. This also helps the process to function more successfully, especially when faced with tight schedules and the danger of deviation.

QA&#8217;s and Unit Testing &#8211; Can QA Create Effective Unit Tests

Unit testing is typically software testing within the developer domain. As the QA role expands in DevOps, QAOps, DesignOps, or within an Agile team, QA testers often find themselves creating unit tests. QA testers may create unit tests within the code using a specified unit testing tool, or independently using a variety of methods.

Project Goal Prioritization in Context of Your Organization&#8217;s Strategic Objectives

One of the most important skills for leaders to have is the ability to prioritize. To understand how we can organize all of the tasks that must be completed in order to complete a project, we must first understand the business we are in, particularly the project goals. There might be several project drivers that stimulate project execution and motivate a company to allocate the appropriate funding.

Three Techniques for Improved Communication and Testing

Anyone who has worked in the software industry for a while can tell you stories about projects that were on the verge of failure. Many initiatives fail even before they reach clients, which is especially disheartening when the failure is fully avoidable.

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ng-mocks automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful