Failing jest test when Expected & Received are the same - jestjs

I'm running into a simple but annoying issue that I feel like I just don't understand how Jest parses and compares results.
it('should throw error when file is encrypted', async () => {
const uint8 = fs.readFileSync('file');
await expect(loadingFile(uint8Array)).rejects.toThrow(TypeError);
});
This test fails & in the terminal I see:
Expected constructor: TypeError
Received constructor: TypeError
typeof(error) on the error itself is an object.
How can I debug this?

Related

Unexpected reserved word 'yield' when running Jest unit tests

I'm using TypeScript and Jest to write unit tests. When I tried to run them, I got the following error messages:
Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
SyntaxError: C:\..\my\file\name.web.spec.ts: Unexpected reserved word 'yield'.
This came from an original TypeScript section like the following:
it("should do things right", () => {
const payload = { ... };
await manager.init(payload);
});
The solution seems obvious in retrospect when looking at the code, but easy to miss. I just simply needed to make the function async.
it("should do things right", async () => {
const payload = { ... };
await manager.init(payload);
});

Cypress dependency module Stub not working and throwing error while running

I've a below JS File
foo.js
const crudService=require(./pg-db-pool)
function allrecords () {
return 3
}
I've the below cypress test file. I'm planning to mock the crudService.listAllRecords and return a constant value.
testfile.spec.js(original)
const foo = require('./foo')
describe('Testing', () => {
beforeEach(() => {
cy.stub(foo, 'allrecords').returns(10)
})
it('crud test - list', async () => {
const list = foo.allrecords()
expect(list).to.equal('10')
})
})
While executing the test run, it's throwing below error because it was not stubbing correctly.
Oops...we found an error preparing this test file:
cypress/integration/api/routes/utils/foo.js
The error was:
Error: Webpack Compilation Error
./node_modules/pg/lib/native/client.js
Module not found: Error: Can't resolve 'pg-native' in './node_modules/pg/lib/native'
resolve 'pg-native' in './node_modules/pg/lib/native'
Parsed request is a module
using description file: ./node_modules/pg/package.json (relative path: ./lib/native)
Field 'browser' doesn't contain a valid alias configuration
Looked for and couldn't find the file at the following paths:
If I comment the first line of foo.js like below, it works fine.
fool.js(modified)
//const crudService=require(./pg-db-pool)
function allrecords () {
return 3
}
Please help me to stub for the scenario mentioned in original foo.js

NodeJS assert does not throw passed error

I have just started using NodeJS's assert Module, and, given that I have understood it correctly, I can pass a custom error instance that should be thrown instead of an AssertionError if the assertion fails.
I.e., the first line in the following code throws an AssertionError and the second line throws an Error:
const assert = require('assert');
assert(false);
assert(false, new Error('abc'));
However, on my system, this does not seem to work. I have the following code:
try {
assert(false, new Error('abc'));
} catch (error) {
console.log(error.constructor.name);
}
and the Output I get is 'AssertionError'. Interestingly, when I try to do the same thing using the REPL, the output is the expected 'Error'.
I use NodeJS v15.8.0 in an alpine Docker container.

Cypress for Electron - Using FS

I am using Cypress to test my Electron application.
Since Cypress uses the browser mode, FS is not supported.
So I am getting this error:
Error in mounted hook: "TypeError: fs.existsSync is not a function"
And I found this on the documentation:
https://docs.cypress.io/api/commands/task.html#Event
So I added this on my test:
it('Sample test', () => {
cy.task('readSettingsJson', settingsFolder).then((content) => {
// This can print the JSON file contents correctly
console.log('content = ' + content)
})
})
And on my plugins/index.js:
on('task', {
readSettingsJson(foldername) {
if (!fs.existsSync(foldername)) {
fs.mkdirSync(foldername, { recursive: true })
// some command to copy the file
} else {
// This is what I am testing at this moment
return fs.readFileSync(path.join(filename, '/settings.json'), 'utf8')
}
return null
}
})
However, it doesnt seem to work. I still get the error:
Error in mounted hook: "TypeError: fs.existsSync is not a function"
And despite the test printing the json file correctly, my app still can't load the JSON file.
Am I missing anything? Help please!
Cypress support for Electron apps are in very early alpha release:
https://www.cypress.io/blog/2019/09/26/testing-electron-js-applications-using-cypress-alpha-release/
As an alternative, try using Spectron, which is the testing framework that is currently recommended by Electron team:
https://www.electronjs.org/spectron

Mocha assertion error: expected {} to be a string

I've been beating my head all morning on this and I'm pretty sure I'm just missing something simple. It appears I'm getting a new object ({}) for a return value when I'm expecting a string, but even if I hard code a string for a return value I get the same error.
I've worked through the examples found here with no trouble. My package.json is set to test properly (or at least I don't think that's the problem, but I can post it as well if it'll help troubleshoot my problem). I'm new-ish to Node.js (but well experienced with JS) & just learning Mocho & Chai.
What am I missing? Why am I getting what appears to be an empty object when I should be getting a string? What's causing the test to fail?
I've written a simple API to get the username from a host PC:
const username = require('username');
exports.getUserName = function() {
console.log(username.sync());
return username.sync();
};
And I've written a test using Mocha & Chai:
var expect = require("chai").expect;
var getUserName = require('./username.js');
describe("User name API", function () {
it("Returns a string with the user's name", function () {
expect(getUserName).to.be.a('string');
});
});
Here's the error that's returned when I run the test with npm test:
> sbserialwidget#0.0.1 test C:\deg\node_modules\sbSerialWidget
> mocha --reporter spec
running
User name API
1) Returns a string with the user's name
0 passing (13ms)
1 failing
1) User name API Returns a string with the user's name:
AssertionError: expected {} to be a string
at Context.<anonymous> (C:\deg\node_modules\sbSerialWidget\test\username.js:6:29)
at callFn (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runnable.js:334:21)
at Test.Runnable.run (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runnable.js:327:7)
at Runner.runTest (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:429:10)
at C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:535:12
at next (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:349:14)
at C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:359:7
at next (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:285:14)
at Immediate._onImmediate (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:327:5)
If I change the test to expect an object, the test works: expect(getUserName).to.be.an('object');.
However if I do a console.log(typeof username.sync()); it says it's a string.
What do I need to do to fix this?
Edit for solution:
Here's the code that I eventually got to work. I think part of the problem was a path issue (I'm in a Windows environment), partly me simply not quite understanding what needed to be done, and finally me not understanding how to call the function properly in the test (see below).
Here's the modified username.js code:
const username = require('username');
exports.getUserName = function() {
console.log(username.sync());
return username.sync();
}
Here's the modified usernametest.js:
var expect = require("chai").expect;
//here's where one point of confusion was, I was trying to call the original getUserName()
//function, but it's been turned into a variable called username
var username = require('..\\js\\username.js').getUserName;
describe("User name API", function () {
it("returns a string with the user's name", function () {
//so here, instead of calling username.getUserName(), I call username()
//instead. Voila, it works...
expect(username()).to.be.a('string');
});
});
you are not executing the function
change
expect(getUserName).to.be.a('string');
to
expect(getUserName()).to.be.a('string');
edit
I din't figure out that your are exporting an object
exports.getUsername = function(){...}
should be
expect(getUserName.getUserName()).to.be.a('string');
thanks to #robertklep

Resources