Fail Protractor on warnings - javascript

I looked through the protractor API and reference conf.js but I couldn't find any documentation on how to fail protractor on warnings or how to turn warnings into errors.
Is either of those possible?

There is nothing built-in in Protractor to treat warnings as errors.
You can redefine the Protractor's log.warn() and throw an error instead of logging a warning:
onPrepare: function () {
var logger = require('protractor/lib/logger.js');
logger.warn = function (message) {
throw message;
};
},
Works for me.
Also, note that:
WARNING - more than one element found for locator ... - the first result will be used
This warning can easily be fixed by replacing the:
element(...)
with:
element.all(...).first()

Related

running cypress test cases with assertion expect(xhr.requestBody.test).to.not.exist, but eslint throws error

cy.wait("api").then((xhr: any) => {
expect(xhr.method).to.eq("POST");
expect(xhr.status).to.eq(200);
expect(xhr.requestBody.test).to.not.exist;
});
expect(xhr.requestBody.test).to.not.exist; this line throws eslint error as shown below:
error Expected an assignment or function call and instead saw an expression #typescript-eslint/no-unused-expressions
Verified at tslint-playground.
Two alternates that pass the linter:
expect(xhr.requestBody).to.not.have.property(test)
expect(xhr.requestBody.test).to.eq(undefined)
In my opinion you have multiple options to solve this:
First and recommended option is to rewrite your assertion for example as follows:
const bodyContainsTest = xhr.requestBody.hasOwnProperty('test');
expect(bodyContainsTest).to.be.false;
Second option would be to simply disable that rule for the next line:
// eslint-disable-next-line #typescript-eslint/no-unused-expressions
expect(xhr.requestBody.test).to.not.exist;
Another option would be to disable this rule globally for all Cypress test files in your .eslintrc.json if needed:
"#typescript-eslint/no-unused-expressions": "off",

Jest gives "Your test suite must contain at least one test" when certain file is imported even though there is a valid test

Whenever I import a certain file from my test file, Jest produces an error that I do not have any tests in the test file, even though there is one with just constants that should pass.
This is running inside a create-react-app folder, but I am using a global install of Jest for the server-side testing.
The Error
FAIL server/__tests__/server.test.js
● Test suite failed to run
Your test suite must contain at least one test.
at onResult (../../../../usr/lib/node_modules/jest/node_modules/#jest/core/build/TestScheduler.js:173:18)
A simplified version of the test file:
const timer = require("./timer.js");
test("should pass", () => {
expect(1 + 2).toBe(3);
});
A simplified version of timer.js:
class Timer {
constructor(ms, onCompleteFunction) {
this.ms = ms;
this.startTime = Date.now();
setTimeout(onCompleteFunction, ms);
}
}
test = () => {
let timer = new Timer(5000, () => console.log("Test Done!"));
};
test();
module.exports = Timer;
(This is a self-answer)
Before adding real testing with Jest, in the Timer.js file I had added a quick test function, just to verify that it was working without running the whole app.
Unfortunately, the function, named test, was not prefixed with var, let, or const. From what I can tell, it overrode the test function from the Jest library, and this error message was the result. When test = 1 or similar was present, the error was
TypeError: test is not a function
This is an extreme edge case due to poor coding practices and something I would have thought was a syntax error on my part, so I don't fault the error message for being unhelpful. I hope this can help someone in the future anyways.

Jest Call retries were exceeded

I have error in the following below test. My node version is : v12.10.0. is there any alternative of setTimeout?
test('demo code', async () => {
const cc = await projectSetup(project);
const onNotification = jest.fn();
cc.sendNotification();
await waitForExpect(() => {
expect(onNotification).toHaveBeenCalledTimes(2);
});
});
The Error log is as
Call retries were exceeded
at ChildProcessWorker.initialize (../../../node_modules/jest-worker/build/workers/ChildProcessWorker.js:230:21)
just add jest.useFakeTimers(); after your imports
...
jest.useFakeTimers();
test('demo code', async () => {
const cc = await projectSetup(project);
const onNotification = jest.fn();
cc.sendNotification();
await waitForExpect(() => {
expect(onNotification).toHaveBeenCalledTimes(2);
});
});
it works in my code
In my case, the actual problem was with the promise handling.
I got the same issue when I was running all my test cases in one go with the jest.
Solution:
Try running one test separately then see what error is coming.
I got the below error after running one problematic test separately where earlier I was getting the Call retries were exceeded:
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read property 'code' of undefined".] {
code: 'ERR_UNHANDLED_REJECTION'
}
With this, I was sure that the problem is with the catch block and when I added it in the async service API function then the test case worked perfectly fine.
Maybe you can also try the same and see if it works for you or not.
I am using the below config:
node: 15.13.0
npm: 7.8.0
jest: 26.6.3
Try running npm doctor using the latest npm version. It's a great tool and it helped me diagnose permission and ownership issues right away.
Takeaway:
Verify File/Folder Permissions & Ownership
Encountered same error when updating the vue-jest version to below listed versions
#vue/vue3-jest: ^27.0.0-alpha.4
#vue/cli-plugin-unit-jest: ~5.0.0,
node: v17.9.0 or v16.14.2
Error disappeared, once downgraded it to node version v14.x.x
Hunch is - the latest node versions are not compatible with the dependencies.
I was able to run the test's successfully doing the following;
Install npm i -D jest-canvas-mock
Update the jest.config.ts file to have:
export default {
...
testEnvironment: "jsdom",
setupFiles: ["jest-canvas-mock"],
}

WebdriverIO Custom Reporter - TypeError: Cannot read property 'write'/'complete' of undefined

I am implementing a custom reporter in WebdriverIO. Following a tutorial (https://webdriver.io/docs/customreporter.html), I have written the following code:
let Reporter = require ('#wdio/reporter').default;
Reporter.reporterName = 'HTMLReporter';
module.exports = class HTMLReporter extends Reporter {
constructor (options) {
options = Object.assign(options, { stdout: true });
super(options);
}
onTestPass (test) {
this.write(`Congratulations! Your test "${test.title}" passed!`);
}
};
When running this code, however, I get the error TypeError: Cannot read property 'write' of undefined. There seems to be an issue with write command in the line this.write('Congratulations! Your test "${test.title}" passed!');.
I am able to bypass this error by changing this.write('Congratulations! Your test "${test.title}" passed!'); to console.log('Congratulations! Your test "${test.title}" passed!');, however when I run this code, I get the error TypeError: Cannot read property 'complete' of undefined. Why am I getting these errors? How can I fix my code to make it run correctly?
since i am facing the same problem, I have decided to replace:
this.write();
with:
fs.writeFileSync();
and it worked as expected

requirejs mocha context error

I have a simple mocha test that fails when using requirejs and the context config.
Here's A.js
define([], function(){
return {};
});
Here's the test spec.js
var requirejs = require('requirejs');
var localReq = requirejs.config({
baseUrl: "./",
context: "context1"
})
describe("context test", function () {
it("should not throw error", function () {
for (var i = 0; i < 100; i++) {
console.log(localReq("A"), i);
}
});
});
When I run the test mocha spec.js, I get the following error:
Uncaught Error: Tried loading "A" at /Users/khirakawa/work/test/node_modules/mocha/bin/A.js then tried node's require("A") and it failed with error: Error: Cannot find module 'A'
Here's a screenshot:
Notice how A was properly loaded and logged 100 times, yet the test still failed. If I comment out the context config, it works just fine.
Mocha is also printing out '1 passing' and '1 failing', even though there is only 1 test.
Why is this happening?
You could write your test like this:
describe("context test", function () {
it("should not throw error", function (done) {
localReq(["A"], function (f) { done(); });
});
});
As you pointed out in a comment, calling localReq to get a module synchronously should work but for some unexplained reason it does not. The code above, which calls localReq to load the module asynchronously, works.
The reason Mocha is saying that your single test is passing and failing is that it is detecting an error that happens after your test is over and has no other test to associate it with. This kind of error message where the same test both passes and fails is a sure indication that you've got something happening asynchronously but that you have not taken care of it in your Mocha test setup.

Categories