javascript – Como “mockar” o “new Date()” utilizando o Jest?

Por favor, alguém sabe como “mockar” o new Date() utilizando o Jest?

Tentei fazer assim, mas não funcionou. A data continua atual:

jest.spyOn(Date, 'now').mockImplementation(() => {
    return new Date(2020, 9, 1, 7).getTime();
})

console.log(new Date());
console.log(new Date(Date.now()));

Resultado:

console.log
  2020-10-30T16:16:44.122Z

console.log
  2020-10-01T10:00:00.000Z

Existe alguma coisa que desconheço. Hum … 🤔

javascript – Jest – mocking a class function from an external node module

I am writing unit tests for a NestJS service, which imports and instantiates a class (OAuth2Client) from an external module (google-auth-library) and uses one of its functions (verifyIdToken).

I am mocking the class to override that function as follows:

// service.test.ts

jest.mock('google-auth-library', () => {
  return {
    OAuth2Client: jest.fn(),
  };
});
import { OAuth2Client } from 'google-auth-library';

describe('test', () => {
  it ('test1', () => {
    OAuth2Client.mockImplementation(() => {
      return {
        verifyIdToken: () => true
      }
    });
  });

  it('test2', () => {
    OAuth2Client.mockImplementation(() => {
      return {
        verifyIdToken: () => false
      }
    });
  });
});

This works correctly and the test passes, but I am seeing a Typescript error saying that mockImplementation does not exist on OAuth2Client and am wondering if this approach is the best way to achieve what I want or is there an alternative. I was reading around and saw that an option is to use jest.spyOn as well.

javascript – Error al pasar parámetrs por post usando jest y nodejs

estoy aprendiendo a hacer tests de integración continua con node, quiero hacer un test al llamar a la ruta /login por post, pero no se como puedo hacer para pasarle los parámetros desde jest, con mi código actual me da un error 500, este es mi código en login.test.js

const request = require('supertest');
const app = require('../routes/login');

describe('Login', () => {
    test('Login correcto', async () => {
        const response = await request(app)
            .post('/login')
            .send({ user: 'hector' })
            .set('user', 'hector')
            .set('Content-Type', 'application/json')
        expect(response.statusCode).toEqual(200)
    });
});

y este el de mi login.js

app.post('/login', (req, res) => {
    let body = req.body;
    let user = body.user;
    console.log(user);
    
    return res.status(200).send('okey');
});

al hacer el test me da un error 500, pero al ejecutar la web normal me sale bién, como puedo mandar usando jest valores por post??, muchas gracias

npm – How do I install jest?

Been trying to install jest with this command:

npm i --global jest

and get these messages:

npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated request-promise-native@1.0.9: request-promise-native has been deprecated because it extends the now deprecated request package, see https://github.com/request/request/issues/3142
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
/Users/user/.nvm/versions/node/v6.11.1/bin/jest -> /Users/user/.nvm/versions/node/v6.11.1/lib/node_modules/jest/bin/jest.js
npm WARN jsdom@16.4.0 requires a peer of canvas@^2.5.0 but none is installed. You must install peer dependencies yourself.
npm WARN ws@7.3.1 requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself.
npm WARN ws@7.3.1 requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself.

+ jest@26.4.2
updated 1 package in 32.731s

Have tried manually installing peer dependencies with:

npm i --save --global canvas@^2.5.0
npm i --save --global bufferutil@^4.0.1
npm i --save --global utf-8-validate@^5.0.2

but still am unable to install jest.

How do I install jest?

vue.js – vuex modules test con jest

Estoy intentando testear un modulo de Vuex que tiene los metodos para registrar usuarios y login usando firebase pero he probado muchisimos ejemplos y siempre obtengo el mismo error. TypeError: Cannot read property ‘getters’ of undefined.
La estructura de mi proyecto es la siguiente. Dentro de la carpeta Store tengo un archivo index.js con el siguiente codigo

   import Vue from 'vue'
   import Vuex from 'vuex'
   import { auth } from './auth.module';

   Vue.use(Vuex)

   export default new Vuex.Store({
     modules: {
        auth
      }
   })

y la definicion de mi modulo en el archivo auth.module.js como sigue

   import AuthService from '../services/auth.service';
   import router from '@/router/index'
   import firebase from 'firebase/app'
   import 'firebase/auth'


export const auth = {

namespaced: true,
state: {
    user: null,
    error: null,
    status: null,
    emailSent: false,
    isLogged: false,
    loading: false
},
mutations: {
    setUser(state, user) {
        state.user = user;
    },
    removeUser(state){
        state.user = null;
    },
    setError(state, error){
        state.error = error;
    },
    setEmailSent(state, value){
        state.emailSent = value;
    },
    setLoading(state, value) {
        state.loading = value;
    },
    setIsLogged(state, value) {
        state.isLogged = value;
    },
    setStatus(state, value) {
        state.status = value;
    }
},
actions: {
    async loginWithFirebase({ commit, state }, user) {

        const promises = ();

        const setPersistence = await AuthService.setPersistence(firebase.auth.Auth.Persistence.SESSION)

        commit('setLoading', true);

        const login = await AuthService.login(user)
            .then((response) => {
                if(!response.user.emailVerified){
                    throw "Correo electrónico no verificado";
                } else {
                    commit('setIsLogged', true);
                    commit('setError', null);
                }
            })
            .catch(error => {
                commit('setError', error);
            })
        

        promises.push(setPersistence);
        promises.push(login);

        Promise.all(promises)
            .then(() => {
                if (state.isLogged === true) {
                    commit('setLoading', false);
                    router.replace('dashboard');
                }     
            })
                       
    },

    async signUpAction({commit}, user){
        commit('setLoading', true);
        await AuthService.signUp(user)
            .then((response) => {
                user.id = response.user.uid;
                commit('setLoading', false);
                commit('setError', null);
               
                this.dispatch('auth/saveUserDB', user);
            })
            .catch(error => {
                commit('setLoading', false);
                commit('setError', error);
            })
          
    },

    async saveUserDB({ commit }, user) { 
        try {
            await AuthService.saveUser(user)
                .then(() => {
                    commit('setError', null)
                    commit('setEmailSent', true)
                    commit('setLoading', false)  
                })
          } catch(error){
              console.error('ha ocurrido un error: ', error.message)
              this.dispatch('auth/removeUserAccount')
          }
    },

    async removeUserAccount() {
        await AuthService.removeUserAccount();
    },

    async getUser({ commit }, uid){  
        await AuthService.getUser(uid)
          .then((doc) => {  
            commit('setUser', doc.data());
          })
          .catch((err) =>{
            console.error(err.code);
          })
    },

    async  signOutAction({commit}){
        firebase.auth().signOut()
        .then(()=>{
          router.replace({name: 'home'})
          commit('setIsLogged', false);
        })
        .catch((error) => {
          commit('setError', error.message);
        })
      },

    async  resetPassword({commit}, email){
        commit('setLoading', true)
        await AuthService.resetPassword(email)
            .then(function() {
                commit('setStatus', 'success');
                commit('setError', null);
            })
            .catch(function(error){
                commit('setLoading', false)
                commit('setStatus', 'failure');
                commit('setError', error);
            })
    }
    
}

}

Probe varios test pero siempre obtengo un error que me muestra la parte del codigo del index donde exporta el store

aqui un ejemplo de test

import {shallowMount , createLocalVue} from '@vue/test-utils'
import Vuex from 'vuex'
import authModule from '@/store/auth.module'


describe('authModule', () => {
   const localVue = createLocalVue();
   localVue.use(Vuex)

   beforeEach(() => {
       store = new Vuex.Store({
           modules: {
              auth: authModule,
          }
       })
    });

   it('set state.user when commit setUser', () =>{

        console.log('running test')
       })
  })

introducir la descripción de la imagen aquí

Se que el test no tiene mucho sentido pero no importa que codigo escriba siempre obtengo el mismo error. Entiendo que es algo al importar el store pero no entiendo que es lo que puede estar funcionando mal

vue.js – como testear que al ocurrir un evento se llame a un metodo vue jest

Estoy tratando de testear un input de tipo email que al ocurrir el evento input llama a un metodo updateDni.
Mi template es el siguiente:

<template>
    <v-text-field
        color="orange"
        hide-details
        label="DNI"
        outlined
        type="string"
        :value="dni"
        :rules="(rules.required, rules.dni)"
        @input="updateDni($event)"
    >
        <div></div>
    </v-text-field>
</template>

y mi metodo es el siguiente:

        
    methods: {
        updateDni(value) {
            this.$emit("input", value);
        }

escribi el siguiente test:

     it('call updateDni when the input change', async () => {

        const wrapper = shallowMount(InputDni, {   
            vuetify: new Vuetify(),
        })

        let updateDniSpy = jest.spyOn(wrapper.vm, 'updateDni')
        const inputField = wrapper.findComponent({ name: 'v-text-field' })
        inputField.element.value = 'fads'
        await inputField.trigger('input')
        expect(updateDniSpy).toHaveBeenCalled()
    });

pero siempre falla indicando que se esperaba que el metodo sea llamado al menos una vez pero la cantidad de llamadas es cero. Estoy empezando con el tema de test y no se como puedo resolver esto

javascript – Cannot read property ‘fromJSON’ of undefined while testing in Jest

while running jest i get the following error.I dont know why am i getting this error.

TypeError: Cannot read property ‘fromJSON’ of undefined

at Object. (node_modules/@grpc/proto-loader/node_modules/protobufjs/ext/descriptor/index.js:3:66)

at Object. (node_modules/@grpc/proto-loader/build/src/index.js:23:20)

Below is the tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "outDir": "dist",
    "sourceMap": true,
    "moduleResolution": "node",
    "declaration": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
    "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "rootDirs": ("."),
    "baseUrl": ".",
    "paths": {
      "@apiV1/*": ("apiV1/*"),
      "@helpers/*": ("helpers/*"),
      "@config/*": ("config/*")
    }
  },

  "include": ("./**/*.ts"),
  "exclude": ("node_modules", "dist")
}

Jest.config.js

// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html

module.exports = {
  // All imported modules in your tests should be mocked automatically
  // automock: false,

  // Stop running tests after the first failure
  // bail: false,

  // Respect "browser" field in package.json when resolving modules
  // browser: false,

  // The directory where Jest should store its cached dependency information
  // cacheDirectory: "/var/folders/ww/57kcc4pj5gj5yg679_s48t840000gq/T/jest_dz",

  // Automatically clear mock calls and instances between every test
  clearMocks: true,

  // Indicates whether the coverage information should be collected while executing the test
  // collectCoverage: false,

  // An array of glob patterns indicating a set of files for which coverage information should be collected
  // collectCoverageFrom: null,

  // The directory where Jest should output its coverage files
  coverageDirectory: "coverage",

  // An array of regexp pattern strings used to skip coverage collection
  // coveragePathIgnorePatterns: (
  //   "/node_modules/"
  // ),

  // A list of reporter names that Jest uses when writing coverage reports
  // coverageReporters: (
  //   "json",
  //   "text",
  //   "lcov",
  //   "clover"
  // ),

  // An object that configures minimum threshold enforcement for coverage results
  // coverageThreshold: null,

  // Make calling deprecated APIs throw helpful error messages
  // errorOnDeprecated: false,

  // Force coverage collection from ignored files usin a array of glob patterns
  // forceCoverageMatch: (),

  // A path to a module which exports an async function that is triggered once before all test suites
  // globalSetup: null,

  // A path to a module which exports an async function that is triggered once after all test suites
  // globalTeardown: null,

  // A set of global variables that need to be available in all test environments
  // globals: {},

  // An array of directory names to be searched recursively up from the requiring module's location
  // moduleDirectories: (
  //   "node_modules"
  // ),

  // An array of file extensions your modules use
  moduleFileExtensions: (
    "ts",
    "tsx",
    "js",
    "jsx"
  ),

  // A map from regular expressions to module names that allow to stub out resources with a single module
  // moduleNameMapper: {},
  "moduleNameMapper": {
    "src/(.*)": "<rootDir>/",
    '^@helpers/(.*)$': '<rootDir>/',
    '^@apiV1/(.*)$': '<rootDir>/',
    '^@config/(.*)$': '<rootDir>/',
  },
  // "modulePaths": (
  //   "<rootDir>",
  // ),
  // "moduleDirectories": (
  //   "node_modules",
  //   "src"
  // ),
  // "moduleFileExtensions": (
  //   'ts', 'tsx', 'js', 'jsx', 'json'
  // ),

  // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
  // modulePathIgnorePatterns: (),

  // Activates notifications for test results
  // notify: false,

  // An enum that specifies notification mode. Requires { notify: true }
  // notifyMode: "always",

  // A preset that is used as a base for Jest's configuration
  // preset: null,

  // Run tests from one or more projects
  // projects: null,

  // Use this configuration option to add custom reporters to Jest
  // reporters: undefined,

  // Automatically reset mock state between every test
  // resetMocks: false,

  // Reset the module registry before running each individual test
  // resetModules: false,

  // A path to a custom resolver
  // resolver: null,

  // Automatically restore mock state between every test
  // restoreMocks: false,

  // The root directory that Jest should scan for tests and modules within
  // rootDir: null,

  // A list of paths to directories that Jest should use to search for files in
  // roots: (
  //   "<rootDir>"
  // ),

  // Allows you to use a custom runner instead of Jest's default test runner
  // runner: "jest-runner",

  // The paths to modules that run some code to configure or set up the testing environment before each test
  // setupFiles: (),

  // The path to a module that runs some code to configure or set up the testing framework before each test
  // setupTestFrameworkScriptFile: null,

  // A list of paths to snapshot serializer modules Jest should use for snapshot testing
  // snapshotSerializers: (),

  // The test environment that will be used for testing
  testEnvironment: "node",

  // Options that will be passed to the testEnvironment
  // testEnvironmentOptions: {},

  // Adds a location field to test results
  // testLocationInResults: false,

  // The glob patterns Jest uses to detect test files
  // testMatch: (
  //   "**/__tests__/**/*.js?(x)",
  //   "**/?(*.)+(spec|test).js?(x)"
  // ),

  // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
  // testPathIgnorePatterns: (
  //   "/node_modules/"
  // ),

  // The regexp pattern Jest uses to detect test files
  testRegex: "(/__tests__/.*|(\.|/)(test|spec))\.(jsx?|tsx?)$",

  // This option allows the use of a custom results processor
  // testResultsProcessor: null,

  // This option allows use of a custom test runner
  // testRunner: "jasmine2",

  // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
  // testURL: "about:blank",

  // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
  // timers: "real",

  // A map from regular expressions to paths to transformers
  transform: {
    "^.+\.(js|jsx|ts|tsx)$": "babel-jest",
  },

  // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
  transformIgnorePatterns: (
    "/node_modules/"
  ),

  // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
  // unmockedModulePathPatterns: undefined,

  // Indicates whether each individual test should be reported during the run
  // verbose: null,

  // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
  // watchPathIgnorePatterns: (),

  // Whether to use watchman for file crawling
  // watchman: true,
};

Can you please help how can i resolve this error.

react.js: drive test https jest request using drills gives TypeError error: can't read property & # 39; end & # 39; indefinite

Hello I have the following code

function handler (…)
{
var req = https.request (options, function (res) {

});

req.on('error', function (e) {
    context.done(null, 'FAILURE');
    return callback(new Error(`Error: ${e.message}`));
});

if (writeContent) {
    req.write(writeContent);
}

req.end();

}
unit testing this function fails in req.on and in req.end
TypeError: Unable to read property & # 39; end & # 39; indefinite
And also TypeError: can't read property & # 39; on & # 39; from undefined

Please help on how I can make fun of these calls.
Thank you!

typescript – nodejs express jest and supertest Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error

I am trying to test with jest + superject to an api made with express.
I am using typescript.
And I am having 2 problems, that the test never closes (I must use –forceExit to finish the console) and even if I get a 200 request, it always returns this error message:

Timeout – Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error: Timeout – Async callback
  was not invoked within the 5000ms timeout specified by jest.setTimeout.

The 2 mistakes
Here is the test code:

const server = require('./../../index');
const app = server.app;
import supertest from 'supertest';

describe("ctrl.home", () => {
    let request: any = null;
    beforeEach((done) => {
        request = supertest(app);
    });

    it("should return 200", async done => {
        const result = await request.get('/');
        console.log(result.statusCode);
        expect(result.statusCode).toBe(200);
        done();
    });
});

reactjs: Jest test with URL object

I have a case where my code is using api API, created as such:

const _url = new URL(window.location.href);

and used like this:

if (_url.searchParams.get('locale')) {
    do something
}

However, in my prank tests I get an error:

TypeError: Cannot read property 'get' of undefined

I have tried to mock globally by doing this in my config file:

global.URL = jest.fn(() => {
  return {
    searchParams: jest.fn(() => {
      return {
        get: jest.fn(() => {
          return '';
        }),
      };
    }),
  };
});

But it doesn't seem to work. Looking at the recorded output of my console _url object, seems to be missing the searchParam property all together:

URL {
  (Symbol(impl)): URLImpl {
    _url: {
      scheme: 'http',
      username: '',
      password: '',
      host: 'localhost',
      port: null,
      path: (Array),
      query: null,
      fragment: null,
      cannotBeABaseURL: false
    },
    (Symbol(wrapper)): (Circular)
  }
}

What am I doing wrong here?