Testing with NPM three mocha+typescript - node.js

I try to add test for my code use three according to Testing-with-NPM
Use typescript + mocha. it works great with following code
const THREE = require('three');
// const ConvexHull = require('three/examples/jsm/math/ConvexHull');
const assert = require('assert');
describe('The THREE object', function() {
it('should have a defined BasicShadowMap constant', function() {
assert.notEqual('undefined', THREE.BasicShadowMap);
}),
it('should be able to construct a Vector3 with default of x=0', function() {
const vec3 = new THREE.Vector3();
assert.equal(0, vec3.x);
// let cc = new ConvexHull();
})
})
but when i uncomment following code and use ConvexHull
const ConvexHull = require('three/examples/jsm/math/ConvexHull');
let cc = new ConvexHull();
I got a error
Error: Cannot find module 'D:\xxx\node_modules\three\examples\jsm\math\ConvexHull'
Use typescript load it with import does not work either.
import * as THREE from 'three';
import { ConvexHull } from 'three/examples/jsm/math/ConvexHull';
And I can't use any class under node_modules\three\examples\jsm.
All of them give a Error: Cannot find module error.
Want to use classes provided under node_modules\three\examples\jsm folder
part of package.json
"scripts": {
"test": "mocha -r ts-node/register test/*.ts --reporter list"
},
"devDependencies": {
"#types/mocha": "^10.0.1",
"#types/node": "^18.11.18",
"#types/three": "^0.148.0",
"mocha": "^10.2.0",
"three": "^0.148.0",
"ts-node": "^10.9.1",
"typescript": "^4.9.4"
}
Don't know how to solve it. any ideas would be appreciated, thanks.

The extension for the file you want to import may be needed.
Node likely struggles to solve the path without it for various reasons.
EDIT:
I tried their code on my PC and added a test case against a "convexHull" object. I have also used the .mjs extension instead of .js to avoid modifying the package.json.
All test cases are okay.
Here is the code:
JAVASCRIPT
unit-test-2.specs.mjs
import * as THREE from 'three';
import assert from "assert";
import {ConvexHull} from 'three/examples/jsm/math/ConvexHull.js';
describe('The THREE object', function ()
{
it('should have a defined BasicShadowMap constant', function ()
{
assert.notEqual('undefined', THREE.BasicShadowMap);
}),
it('should be able to construct a Vector3 with default of x=0', function ()
{
const vec3 = new THREE.Vector3();
assert.equal(0, vec3.x);
})
it("should have the convexHull tolerance set to -1", function ()
{
let cc = new ConvexHull();
assert.equal(cc.tolerance, -1);
})
})
To run the test:
npm test
I am adding the package.json, so you can compare the dependency versions:
package.json
{
"scripts": {
"test": "mocha --reporter list"
},
"devDependencies": {
"mocha": "^10.2.0",
"three": "^0.148.0"
}
}
TYPESCRIPT
The "Three" module contains a type declaration file "index.d.ts". However, it does not expose the class ConvexHull as it's not part of Three core codes.
Because of this, copy the example folder in your root directory (outside the node_modules, at least).
Create a tsconfig.json within your test directory so it does not affect your main tsconfig:
πŸ“ test/tsconfig.json ↴
{
"compilerOptions": {
"allowJs": true,
"checkJs": false // <- Optional
}
}
Create .mocharc.json to make Mocha aware of how to run the tests
πŸ“ .mocharc.json ↴
{
"extensions": ["ts"],
"require": [
"test/register-test.js"
],
"spec": [
"test/**/*.spec.ts"
]
}
Create the file the .mocharc is referring to:
πŸ“ register.js ↴
require("ts-node").register({
project: "test/tsconfig.json"
});
package.json to compare versions
πŸ“ package.json ↴
{
"scripts": {
"test": "mocha --config test/.mocharc.json"
},
"devDependencies": {
"#types/mocha": "^7.0.2",
"#types/node": "^18.11.18",
"mocha": "^10.2.0",
"ts-node": "^8.9.0",
"typescript": "^3.8.3"
},
"dependencies": {
"#types/three": "^0.148.0",
"three": "^0.148.0"
},
"type": "commonjs"
}
Update the tests:
πŸ“ test/unit/unit-test.js ↴
import { strict as assert } from 'node:assert';
import * as THREE from 'three';
import {ConvexHull} from '../../examples/jsm/math/ConvexHull';
describe('The THREE object', function ()
{
it('should have a defined BasicShadowMap constant', function ()
{
console.log(THREE.BasicShadowMap);
assert.notEqual(undefined, THREE.BasicShadowMap);
})
it('should be able to construct a Vector3 with default of x=0', function ()
{
const vec3 = new THREE.Vector3();
assert.equal(0, vec3.x);
})
it("should have the convexHull tolerance set to -1", function ()
{
let cc = new ConvexHull();
assert.equal(cc.tolerance, -1);
})
})
I have a structure like that:
πŸ“ root
β”‚
β””β”€β”€β”€πŸ“ examples
β”‚ β””β”€β”€β”€πŸ“ jsm
β”‚ β””β”€β”€β”€πŸ“ math
β”‚ πŸ“ ConvexHull.js
β””β”€β”€β”€πŸ“ test
β”‚ │─ πŸ“ .mocharc.json
β”‚ │─ πŸ“ .register-test.js
β”‚ │─ πŸ“ .tsconfig.json
β”‚ β””β”€β”€β”€πŸ“ unit
β”‚ πŸ“ unit-test.ts
β”‚
│─ πŸ“ package.json
Run the test
npm test
All test cases will pass.
Note: I might update this post

Related

Can't mock a ES6 imported function in NodeJS

I've been trying for some time to mock the fetchLiveMatches imported function with no success. I've been browsing for some ideas but I think I ran out of it, so I could use some help. Any ideas of what I am doing wrong?
live.test.js
import * as liveController from "./live";
import { jest } from "#jest/globals";
import * as liveService from "../service/live";
import { buildReq, buildRes, buildNext } from "../utils/testingHelper";
jest.mock("../service/live");
beforeEach(() => {
jest.clearAllMocks();
});
describe("Live Controller", () => {
test("calls fetchLiveMatches function to fetch from external API", async () => {
const req = buildReq();
const res = buildRes();
const next = buildNext();
await liveController.getLiveMatches(req, res, next);
expect(next).not.toHaveBeenCalled();
expect(liveService.fetchLiveMatches).toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(500);
expect(res.status).toHaveBeenCalledTimes(1);
});
});
service/live.js
import axios from "axios";
async function fetchLiveMatches() {
// Some hidden code
return axios({
method: "get",
url: `${API_FOOTBALL_BASE_URL}${GET_EVENTS}${MATCH_LIVE}${WIDGET_KEY}${TIMEZONE}${DETAILS}`,
headers: {}
}).then(res => res.data);
}
export { fetchLiveMatches };
jest.config.js
export default {
testEnvironment: "jest-environment-node",
transform: {}
};
package.json
{
"name": "server",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"license": "MIT",
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"axios": "^1.1.3",
"eslint": "^8.26.0",
"jest": "^29.2.2",
"prettier": "^2.7.1"
},
"scripts": {
"start": "node --watch index.js",
"start:no-watch": "node index.js",
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch"
}
}
Test Error Output
Live Controller β€Ί calls fetchLiveMatches function to fetch from external API
expect(received).toHaveBeenCalled()
Matcher error: received value must be a mock or spy function
Received has type: function
Received has value: [Function fetchLiveMatches]
Just posting the solution I found for anyone who eventually is facing the same problem:
First, since I'm using ES6/module imports without Babel I changed the mock function to unstable_mockModule, and then based on the docs I decided to try dynamic imports in test scope after mocking the modules.
If you're using ES module imports then you'll normally be inclined to put your import statements at the top of the test file. But often you need to instruct Jest to use a mock before modules use it. For this reason, Jest will automatically hoist jest.mock calls to the top of the module (before any imports). To learn more about this and see it in action, see this repo.
The test component works with the following code:
import { jest } from "#jest/globals";
import { buildReq, buildRes, buildNext } from "../utils/testingHelper";
describe("Live Controller", () => {
test("calls fetchLiveMatches function to fetch from external API", async () => {
jest.unstable_mockModule("../service/live", () => ({
fetchLiveMatches: jest.fn(() => [])
}));
const { getLiveMatches } = await import("./live");
const { fetchLiveMatches } = await import("../service/live");
const req = buildReq();
const res = buildRes();
const next = buildNext(msg => console.log(msg));
await getLiveMatches(req, res, next);
expect(fetchLiveMatches).toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(200);
expect(res.status).toHaveBeenCalledTimes(1);
});
});

Testing NodeJS with Mocha: 'Require is not defined'

EDIT:
As per the comment on the answer below: removing "type": "module" from package.json, which as I understand it is what makes Node understand 'import' and 'export' statements, and reverting everything to 'require' and 'module.exports' solved the issue.
Is there a way to keep 'import' and 'export' and still make Mocha work?
I have a very simple Node file that I'm trying to test with Mocha/Chai. The actual code is trivial, this is just to learn a bit about Mocha and how to use it. But when I run the Mocha test, I get the error ERROR: ReferenceError: require is not defined
`
I did some googling for people experiencing the same problem but the examples that I came up with were when they were running the test in the browser (see, for example, Mocha, "require is not defined" when test in browser).
The file I want to test, index.js
const argv = require('minimist')(process.argv.slice(2));
const digitTester = /\d/g;
const capTester = /[A-Z]/g;
const dict = {
length:10,
must_have_numbers: true,
must_have_caps: true
}
export default function passwordCheck(password) {
if (!password) return false;
if (typeof password !== "string") return false;
if (password.length < dict.length) return false; // assumes that 10 is a MINIMUM length
if (dict.must_have_numbers && !digitTester.test(password)) return false;
return !(dict.must_have_caps && !capTester.test(password));
}
if (argv._.length) {
console.log(passwordCheck(argv._[0]))
}
/**
* alternate version to check a lot of passwords:
*
* if (argv._.length) {
* for (const pwd of argv_) console.log(passwordCheck(pwd)
*}
*
*/
the mocha file, test/index.test.js
const chai = require('chai')
const expect = chai.expect
const passwordCheck = require('../index.js')
const tooShort = "A2a"
const noCaps = "a2abcdefghijklmnop"
const noNumber = "Aabcdefghijklmnop"
const good = "A2abcdefghijklmnop"
describe('password checking', () => {
it('should return false for passwords less than length 10', () => {
expect(passwordCheck(tooShort)).to.be.false;
});
it('should return false for passwords without a capital letter', () => {
expect(passwordCheck(noCaps)).to.be.false;
});
it('should return false for passwords without a number', () => {
expect(passwordCheck(noNumber)).to.be.false;
});
it('should return true for passwords that match criteria', () => {
expect(passwordCheck(good)).to.be.true;
});
});
and package.json
{
"name": "codetest",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"scripts": {
"test": "mocha"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"#types/minimist": "^1.2.1",
"#types/node": "^14.14.20",
"chai": "^4.2.0",
"minimist": "^1.2.5",
"mocha": "^8.2.1"
}
}
and the error message is
βœ– ERROR: ReferenceError: require is not defined
at file:///Users/r/Documents/Projects/sandbox/pwd_checker/index.js:2:14
at ModuleJob.run (node:internal/modules/esm/module_job:152:23)
at async Loader.import (node:internal/modules/esm/loader:166:24)
at async exports.handleRequires (/Users/r/Documents/Projects/sandbox/pwd_checker/node_modules/mocha/lib/cli/run-helpers.js:94:28)
at async /Users/r/Documents/Projects/sandbox/pwd_checker/node_modules/mocha/lib/cli/run.js:341:25
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Node 15.
Remove this line - "type": "module" from package.json and check whether it’s working or not.
Prepend your tests with the following:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
This is because you cannot require from an ESM module; for more info please see this comment on a nodejs issue.
Documentation: https://nodejs.org/api/esm.html#differences-between-es-modules-and-commonjs

Create React App doesn't properly mock modules from __mocks__ directory

I have a working example with Jest and mocks from __mocks__ directory that works :
With simple Jest setup
// package.json
{
"name": "a",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "jest"
},
...
"devDependencies": {
"jest": "^26.6.3"
},
"dependencies": {
"#octokit/rest": "^18.0.12"
}
}
And then /index.js :
const { Octokit } = require("#octokit/rest");
const octokit = new Octokit();
module.exports.foo = function() {
return octokit.repos.listForOrg({ org: "octokit", type: "public" })
}
with its test (/index.test.js):
const { foo } = require("./index.js");
test("foo should be true", async () => {
expect(await foo()).toEqual([1,2]);
});
and the mock (/__mocks__/#octokit/rest/index.js):
module.exports.Octokit = jest.fn().mockImplementation( () => ({
repos: {
listForOrg: jest.fn().mockResolvedValue([1,2])
}
}) );
This works quite well and tests pass.
With Create React App
However doing the same with Create React App seems to be giving me a weird result:
// package.json
{
"name": "b",
"version": "0.1.0",
"dependencies": {
"#octokit/rest": "^18.0.12",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
...
}
And then /src/foo.js:
import { Octokit } from "#octokit/rest";
const octokit = new Octokit();
module.exports.foo = function() {
return octokit.repos.listForOrg({ org: "octokit", type: "public" })
}
with its test (/src/foo.test.js):
const { foo} = require("./foo.js");
test("foo should be true", async () => {
expect(await foo()).toEqual([1,2]);
});
and the very same mock (under /src/__mocks__/#octokit/rest/index.js):
export const Octokit = jest.fn().mockImplementation( () => ({
repos: {
listForOrg: jest.fn().mockResolvedValue([1,2])
}
}) );
This makes the test fail:
FAIL src/foo.test.js
βœ• foo should be true (2 ms)
● foo should be true
expect(received).toEqual(expected) // deep equality
Expected: [1, 2]
Received: undefined
2 |
3 | test("foo should be true", async () => {
> 4 | expect(await foo()).toEqual([1,2]);
| ^
5 | });
6 |
7 |
at Object.<anonymous> (src/foo.test.js:4:25)
After reading a lot it seems that I can't make __mocks__ work inside Create React App. What's the problem?
The problem is that CRA's default Jest setup automatically resets the mocks, which removes the mockResolvedValue you set.
One way to solve this, which also gives you more control to have different values in different tests (e.g. to test error handling) and assert on what it was called with, is to expose the mock function from the module too:
export const mockListForOrg = jest.fn();
export const Octokit = jest.fn().mockImplementation(() => ({
repos: {
listForOrg: mockListForOrg,
},
}));
Then you configure the value you want in the test, after Jest would have reset it:
import { mockListForOrg } from "#octokit/rest";
import { foo } from "./foo";
test("foo should be true", async () => {
mockListForOrg.mockResolvedValueOnce([1, 2]);
expect(await foo()).toEqual([1, 2]);
});
Another option is to add the following into your package.json to override that configuration, per this issue:
{
...
"jest": {
"resetMocks": false
}
}
This could lead to issues with mock state (calls received) being retained between tests, though, so you'll need to make sure they're getting cleared and/or reset somewhere.
Note that you generally shouldn't mock what you don't own, though - if the interface to #octokit/rest changes your tests will continue to pass but your code won't work. To avoid this issue, I would recommend either or both of:
Moving the assertions to the transport layer, using e.g. MSW to check that the right request gets made; or
Writing a simple facade that wraps #octokit/rest, decoupling your code from the interface you don't own, and mocking that;
along with higher-level (end-to-end) tests to make sure everything works correctly with the real GitHub API.
In fact, deleting the mocks and writing such a test using MSW:
import { rest } from "msw";
import { setupServer } from "msw/node";
import { foo } from "./foo";
const server = setupServer(rest.get("https://api.github.com/orgs/octokit/repos", (req, res, ctx) => {
return res(ctx.status(200), ctx.json([1, 2]));
}));
beforeAll(() => server.listen());
afterAll(() => server.close());
test("foo should be true", async () => {
expect(await foo()).toEqual([1, 2]);
});
exposes that the current assumption about what octokit.repos.listForOrg would return is inaccurate, because this test fails:
● foo should be true
expect(received).toEqual(expected) // deep equality
Expected: [1, 2]
Received: {"data": [1, 2], "headers": {"content-type": "application/json", "x-powered-by": "msw"}, "status": 200, "url": "https://api.github.com/orgs/octokit/repos?type=public"}
13 |
14 | test("foo should be true", async () => {
> 15 | expect(await foo()).toEqual([1, 2]);
| ^
16 | });
17 |
at Object.<anonymous> (src/foo.test.js:15:25)
Your implementation should actually look something more like:
export async function foo() {
const { data } = await octokit.repos.listForOrg({ org: "octokit", type: "public" });
return data;
}
or:
export function foo() {
return octokit.repos.listForOrg({ org: "octokit", type: "public" }).then(({ data }) => data);
}

How can I ignore "-!svg-react-loader!./path/to/my.svg" when testing with Jest without bundling everything with webpack

We're using svg-react-loader for some of the SVG files in our application. We're trying to setup jest to run with a babel-jest and the following .babelrc:
{
"presets": [
"es2015",
"react"
],
"plugins": [
"transform-decorators-legacy",
"transform-class-properties",
"transform-object-rest-spread"
]
}
The following test fails:
/* global it, document */
import React from 'react'
import ReactDOM from 'react-dom'
import Comp from './Icon'
it('renders without crashing', () => {
const div = document.createElement('div')
ReactDOM.render(<Comp><div /></Comp>, div)
})
With error:
Cannot find module '-!svg-react-loader!../../assets/grid.svg' from 'Icon.js'
How could I ignore imports that start with like import grid from '-!svg-react-loader!../../assets/grid.svg' in jest?
The way I solved this was by adding a jest mock for any import that contains -!svg-react-loader! at the beginning of the module.
"moduleNameMapper": {
"^-!svg-react-loader.*$": "<rootDir>/config/jest/svgImportMock.js"
}
Where svgImportMock.js is:
'use strict';
module.exports = 'div';
It's not ideal, because the file could simple not exists, but the assumption is that we see the missing module when bundling with webpack.
I resolved this by installing jest-svg-transformer, then adding this config:
{
"jest": {
"transform": {
"^.+\\.svg$": "jest-svg-transformer"
}
}
}
I was able to solve this by correctly handling static assets in Jest (https://jestjs.io/docs/en/webpack#handling-static-assets):
// package.json
{
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}
}
}
// __mocks__/styleMock.js
module.exports = {};
// __mocks__/fileMock.js
module.exports = 'test-file-stub';

React unit test with jest in es6

I am pretty new in react world and trying to write simple friendslist application. I wrote my friends store in es6 style and using babel as transpiler from es5 to es6.
import AppDispatcher from '../dispatcher/app_dispatcher';
import { EventEmitter } from 'events';
import FRIENDS_CONST from '../constants/friends';
const CHANGE_EVENT = 'CHANGE';
let friendsList = [];
let add = (name) => {
let counter = friendsList.length + 1;
let newFriend = {
id: counter,
name: name
};
friendsList.push(newFriend);
}
let remove = (id) => {
let index = friendsList.findIndex(e => e.id == id);
delete friendsList[index];
}
let FriendsStore = Object.assign({}, EventEmitter.prototype, {
getAll: () => {
return friendsList;
},
emitChange: () => {
this.emit(CHANGE_EVENT);
},
addChangeListener: (callback) => {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: (callback) => {
this.removeListener(CHANGE_EVENT, callback);
}
});
AppDispatcher.register((action) => {
switch (action.actionType) {
case FRIENDS_CONST.ADD_FRIENDS:
add(action.name);
FriendsStore.emitChange();
break;
case FRIENDS_CONST.REMOVE_FRIENDS:
remove(action.id);
FriendsStore.emitChange();
break;
}
});
export default FriendsStore;
Now I want to test my store and wrote the unit test also in es6
jest.dontMock('../../constants/friends');
jest.dontMock('../friends_store');
describe('FriendsStore', () => {
import FRIENDS from '../../constants/friends';
import AppDispatcher from '../../dispatcher/AppDispatcher';
import FriendsStore from '../friends_store';
let FakeAppDispatcher;
let FakeFriendsStore;
let callback;
let addFriends = {
actionType: FRIENDS.ADD_FRIENDS,
name: 'Many'
};
let removeFriend = {
actionType: FRIENDS.REMOVE_FRIENDS,
id: '3'
};
beforeEach(function() {
FakeAppDispatcher = AppDispatcher;
FakeFriendsStore = FriendsStore;
callback = AppDispatcher.register.mock.calls[0][0];
});
it('Should initialize with no friends items', function() {
var all = FriendsStore.getAll();
expect(all).toEqual([]);
});
});
When I execute the test with statement npm test, I've got the error message:
> react-starterify#0.0.9 test /Volumes/Developer/reactjs/app5
> echo "Error: no test specified"
Error: no test specified
What am I doing wrong? The file structure looks as follow:
I did it following the tutorial:
npm install --save-dev jest babel-jest babel-preset-es2015 babel-preset-react react-test-renderer
then
add to package.json
"scripts": {
"test": "jest"
},
"jest": {
"testPathDirs": [
"src/main/resources/web_pages/__tests__"
]
},
Result:
PASS src/main/resources/web_pages/__tests__/modules/utils/ValidationUtil.spec.js (5.214s)
βœ“ ValidateEmail (5ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 6.092s, estimated 7s
Ran all test suites.
To test ES6 syntax and JSX files, they need to be transformed for Jest. Jest has a config variable where you can define a preprocessor (scriptPreprocessor). You can use the babel-jest preprocessor:
Make the following changes to package.json:
{
"devDependencies": {
"babel-jest": "*",
"jest-cli": "*"
},
"scripts": {
"test": "jest"
},
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"testFileExtensions": ["es6", "js"],
"moduleFileExtensions": ["js", "json", "es6"]
}
}
And run:
$ npm install

Resources