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

I am trying to test with jest + superject to an API made with express.
I use tapuscript.
And I have 2 problems, that the test never closes (I have to use –forceExit to end the console) and even if I get the request back to 200, it always returns this error message:

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

The 2 errors
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("https://es.stackoverflow.com/");
        console.log(result.statusCode);
        expect(result.statusCode).toBe(200);
        done();
    });
});

javascript – Import of mocks in react / jest with the ESLint no-mocks-import rule

So I am a little confused by this rule and I hit a wall while trying to fix it. The description says that I should not import any __mocks__ directories manually. Currently, I have this:

import { Breadcrumbs as BreadcrumbsView } from '../../__mocks__'

Which of course leads to this ESLint error. the __mocks__ has directly subdictionaries and a index.js file which exports all the necessary simulations from these sub-jurisdictions.

The model itself is simple:

import React from 'react'


export const Breadcrumbs = (props) => (
  
{props?.children}
)

If I do this:

jest.mock('../../__mocks__')

const { Breadcrumbs: BreadcrumbsView } = import('../../__mocks__')

Then this rule passes (not even sure it's even the right solution, because I still have __mocks__ in the way), but the rule import/no-commonjs failed since i used require.

If I use import there instead of require I get the following error when I run the test:

Test suite failed to run

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

/*path-to-project*/packages/app/src/lib/breadcrumbs/__tests__/utils/getBreadcrumbContext.test.js:37
var _ref = import('../../__mocks__'),
           ^^^^^^

SyntaxError: Unexpected token import

  at ScriptTransformer._transformAndBuildScript (../../node_modules/jest-runtime/build/script_transformer.js:403:17)

Could someone explain the solution and what am i doing wrong?

Let me also note that I am using Node version 10.13.0. Maybe this is somehow related.

javascript – TryCatch Unit testing with Jest

I am trying to test tryCatch code with a joke but keep getting errors, currently this is what I have tried

student.js

async checkStudentExist(studentName) {
        try {
            const studentExist = await this.StudentRepository.getOne({name: studentName})
            if (studentExist) {
                throw new Error(`Student already exist with the name: ${studentName}`)
            }
            return studentExist
        } catch (error) {
            throw error   
        }
    }

student.test.js

it('should throw an error if the input name already exist in database', async () => {
    mockGetOne.mockReturnValue(Promise.resolve(expectedOrganization))
    await studentService.checkStudentExist('john doe')
    expect(mockGetOne).toHaveBeenCalledWith({name: 'sample org'})
    expect(studentService.checkStudentExist('john doe')).resolves.toThrowError(new Error(`Organization already exist with the name: john doe`))
})

Jest encountered an unexpected token when using Typescript, React and SPFx

describe('Enzyme basics', () => {

  let reactComponent: ReactWrapper;

  beforeEach(() => {

    reactComponent = mount(React.createElement(
      Crud,
      {
        spHttpClient: {},
        siteUrl: 'bogus',
        description: 'bogus'
      }
    ));
  });

  afterEach(() => {
    reactComponent.unmount();
  });

  it('should root web part element exists', () => {

    // define the css selector
    let cssSelector: string = '#iceCreamShop';

    // find the element using css selector
    const element = reactComponent.find(cssSelector);
    expect(element.length).toBeGreaterThan(0);
  });

});

I'm trying to run this test, but for some reason, Jest is throwing me an error.

  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    C:UsersadminDesktopgithubcrud-simple-testnode_modules@microsoftsp-httplibindex.js:12
    export { default as HttpClient } from './httpClient/HttpClient';
    ^^^^^^

    SyntaxError: Unexpected token export



      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1059:14)
      at Object. (src/webparts/crud/components/Todolist/Todolist.tsx:7025:27)

  console.log src/webparts/crud/components/Store/reducers.ts:486
    action type @@redux/INIT3.m.1.6.8.p is not found

I have tried different things, but I have no idea how to fix it. This is my package.json. I am using a Typescript React application using SPFx. I think it's a problem with the Microsoft library in particular, but maybe it's just a configuration problem.

This is my most pleasant configuration inside package.json:

"jest": {
    "moduleFileExtensions": (
      "ts",
      "tsx",
      "js"
    ),

    "transformIgnorePatterns": ( "/node_modules/" ),
    "transform": {
      "^.+\.(js|ts|tsx)$": "ts-jest"
    },
    "testMatch": (
      "**/src/**/*.test.+(ts|tsx|js)"
    ),
    "collectCoverage": true,
    "coverageReporters": (
      "json",
      "lcov",
      "text",
      "cobertura"
    ),
    "coverageDirectory": "/jest",
    "moduleNameMapper": {
      "\.(css|less|scss|sass)$": "identity-obj-proxy"
    },
    "testResultsProcessor": "jest-junit",
    "coverageThreshold": {
      "global": {
        "branches": 100,
        "functions": 100,
        "lines": 100,
        "statements": 100
      }
    }
  }

Now this seems to be related to the fact that I am using Typescript, but the error does not tell me what exactly the problem is and what exactly I should do with my configuration file. In fact, I think the log is misleading because the second error points to a js file and not a ts file.

unit tests – Jest coverage difference between local (Windows) and server in a single file

I have a Vue project with unit tests, and we have a Jenkins generation server that builds and tests feature branches before we can merge them into the development branch. Right now, I have a really strange difference between code coverage reports between when I run the tests locally and the report on the generation server. I have already tried throwing node_modules to see if this fixes something, but it is not.

For a file, when I run tests locally, I get these results:

  MyComponent.vue                  |    57.89 |       25 |    33.33 |    76.92 |          68,75,81 |

On Jenkins, I get:

  MyComponent.vue                  |       25 |      100 |      100 |       25 |          58,64,69 |

This is the only file where this occurs. For all other files, the results are identical.

One possible culprit may be the fact that I am using Windows. Mac users on my team get the same results as Jenkins. However, shouldn't the knot and the joke work the same on both platforms?

And why would this happen only for this file, and not for any other? This file is nothing unique. It is a View component. A fairly simple one. It uses javascript while most of our components use the script, but it is not the only javascript component. It imports another component, has properties, data, a calculated property, and a method. As far as I know, this file is really nothing strange.

I don't know if this is caused by Windows vs Unix (seems likely), by Jest, by Vue or by js vs ts. I am completely perplexed.

Is it possible to run a few sets of test cases for the production environment and some sets of test cases for the environment uat using the framework jest

Is it possible to run a few sets of test cases (eg, "get data" cases) for the production environment and some test case sets (bot get and post data data) for the environment uat using the jest framework

javascript – Matchers viewjs jest unit test

I work with a project that already integrated unit tests and tests provided by some analyzers to help validate certain expectations. How can I get the full scope of my project to see these meters?

Today, I declare them like this:

const customMatchers = {}

customMatchers.toBeAViewComponent = function(options) {
  ...
}

global.expect.extend(customMatchers)

But I get the following comments when I run the tests:
back of the test run using matcher

reactjs – Test Jest / Enzyme if the page is redirected after a click of a button

I write unit tests with Jest and Enzyme. I have a button on a 404 page that should redirect a user to the home page of the websites. I want to write a test to verify that this button redirects a user to the home page, regardless of the URL. In other words, the test must succeed if the click of the button brings a user to the homepage and must not press href.

Until now, I have the code to click on my button, which should redirect the user.

it('redirects when HOMEPAGE button is clicked', () => {
    const wrapper = mount();
    const link = wrapper.find('#page-not-found-link').first();
    link.simulate('click');
    expect()
})

When the button is clicked, we should be routed to so I tried to add:

it('redirects when HOMEPAGE button is clicked', () => {
    const wrapper = mount();
    const newComp = mount ();
    const link = wrapper.find('#page-not-found-link').first();
    const buttonClick = link.simulate('click');
    expect(buttonClick).toEqual(newComp)
})

It seems that I need to compare with the result of clicking on the button but I have not yet found a work solution.

node.js – Configure async on tests with Jest, Nodejs, Express and Mongodb

Hello, I'm new to Javascript, and I'm developing an api with nodejs, express and mongodb. In tests, I use Jest, Supertest, Factory Girl, Faker and another instance of mongodb in Docker, that is, I do not make fun of my database. My S.O. is Ubuntu.

I have trouble running the integration tests because of a problem that I believe consists of erasing the bank data before each test.

When I run a test suite at a time, everything happens normally.

enter the description of the image here

However, when I run all the test suites together, random errors related to the database data occur.

enter the description of the image here

In this impression, the error was related to UserController.js, but sometimes errors occur in other controllers, errors and files occur randomly.

I think this could be related to my database cleanup function. It is an asynchronous function. It seems to me that when these errors occur, it is because the execution and the finalization of the cleansing of the database during the new test are long. which ultimately invalidates the current test.

This is my Jest installation file:

import '../src/bootstrap';

import databaseHelper from '../src/app/helpers/database';

beforeAll(() => {
  return databaseHelper.connect();
});

beforeEach(() => {
  return databaseHelper.truncate();
});

afterAll(() => {
  return databaseHelper.disconnect();
});

This is my database assistant:

import mongoose from 'mongoose';

import databaseConfig from '../../config/database';

const connect = async () => {
  if (mongoose.connection.readyState === 0) {
    await mongoose.connect(databaseConfig.uri, databaseConfig.options);
  }
};

const truncate = async () => {
  const models = mongoose.connection.modelNames();
  const promises = models.map(async model =>
    mongoose.connection.model(model).deleteMany({})
  );
  await Promise.all(promises);
};

const disconnect = async () => {
  await mongoose.disconnect();
};

export default {
  connect,
  truncate,
  disconnect,
};

My database settings:

export default {
  uri: process.env.DB_URL,
  options: {
    useCreateIndex: true,
    useNewUrlParser: true,
    useFindAndModify: false,
  },
};

In almost all my tests, I create a database record with Factory girl and Faker and use Supertest to query and analyze the answer, as in this example below:

it('should not be able to create user with duplicate email', async done => {
    const user = await factory.build('User');

    let response = await request.post('/users').send({
      name: user.name,
      email: user.email,
      password: user.password,
    });

    expect(response.status).toBe(200);
    expect(response.body).toHaveProperty('id');
    expect(response.body).toHaveProperty('name', user.name);
    expect(response.body).toHaveProperty('email', user.email);

    response = await request.post('/users').send({
      name: user.name,
      email: user.email,
      password: user.password,
    });

    expect(response.status).toBe(400);
    expect(response.body).toHaveProperty('error', 'User already exists');

    done();
  });

Here is the configuration of Factory Girl:

import faker from 'faker';
import { factory, MongooseAdapter } from 'factory-girl';

import User from '../src/app/models/User';
import Habit from '../src/app/models/Habit';

const adapter = new MongooseAdapter();

factory.setAdapter(adapter);

factory.define('User', User, {
  name: faker.name.findName(),
  email: faker.internet.email(),
  password: faker.internet.password(),
});

factory.define('Habit', Habit, {
  name: faker.lorem.word(),
  description: faker.lorem.sentence(),
});

export default factory;

These are my dependencies:

  "dependencies": {
    "bcryptjs": "^2.4.3",
    "dotenv": "^8.1.0",
    "express": "^4.17.1",
    "joi": "^14.3.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.6.11",
    "mongoose-paginate": "^5.0.3"
  },
  "devDependencies": {
    "@sucrase/jest-plugin": "^2.0.0",
    "@types/jest": "^24.0.18",
    "eslint": "^6.3.0",
    "eslint-config-airbnb-base": "^14.0.0",
    "eslint-config-prettier": "^6.1.0",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-prettier": "^3.1.0",
    "factory-girl": "^5.0.4",
    "faker": "^4.1.0",
    "jest": "^24.9.0",
    "nodemon": "^1.19.1",
    "prettier": "^1.18.2",
    "sucrase": "^3.10.1",
    "supertest": "^4.0.2"
  }

The full code is on github: https://github.com/dyarleniber/habit-tracker-back-end

Can any one please tell me what I did wrong? Or give me suggestions for improvement?

Another interesting point, I noticed that after running the tests several times, I noticed that many processes were running on my machine with these commands:

USER 999 COMANDO mongodb --bind_ip_all

USER  COMANDO node_modulesjest-wo

How to test the PNP with JEST?

Is there a way to make fun of the context of the Webpart, because I need it to make a request via pnp?