can you help with my sync-problem in mocha test?
I have this test in mocha, I use wd-sync and resemble packages.
wd-sync is for avoiding Promises and callback hell and it is great package, but I figured out that it has some problems. It doesn't wait for resemble so this part is executed out of test cases. I tried add resemble to Promise but without success so now I am out of ideas.
This is my log from mocha - As you can see, console.log(inside) is executed out of test cases PROMISE_002, test pass, but it should fails. After all hook fails, because expected is executed during this step.
Screenshot functionality
1
2
3
4
✓ PROMISE_002 (3714ms)
inside
inside2
1) "after all" hook
1 passing (16s)
1 failing
1) Screenshot functionality "after all" hook:
Uncaught AssertionError: expected '0.01' to equal 5
My test:
it.only('PROMISE_002', wrap(function(){
const date = new Date();
const path = `${date.getFullYear()}${date.getMonth()}${date.getDate()}`;
const dir = `archiveServer/${path}`;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
console.log(1);
driver.saveScreenshot(`archiveServer/baseline/PROMISE_002.png`);
console.log(2);
driver.saveScreenshot(`${dir}/PROMISE_002.png`);
console.log(3);
resemble(`${dir}/PROMISE_002.png`)
.compareTo('archiveServer/baseline/PROMISE_002.png')
.onComplete(function (data) {
//if (data.misMatchPercentage > 0.5) {
console.log('inside');
data.getDiffImage()
.pack()
.pipe(fs.createWriteStream(`${dir}/PROMISE_002-diff.png`));
console.log('inside2');
expect(data.misMatchPercentage).to.equal(5);
});
console.log('4');
}));
Related
how to mock a promise in jest-test?
till now, we were using launchDarkly.getFlag directly without waiting for the onInitialization method/promise? so the tests had it mocked
// in myFunc.test.js file
jest.spyOn(launchDarkly, 'getFlag').mockImplementation(() => true);
But now that it has changed as mentioned below, the test(s) has started to fail, so what and how should I mock so that the test-flow is checked with isWhiteSpaceFeatureEnabled variable being tested against an if check?
// in componentUtility.js file
// before isWhitespaceOvertimeFeatureEnabled = launchDarkly.getFlag(WHITESPACE_OVERTIME_CHART_FLAG, false);
launchDarkly.onInitialization().then(() => {
isWhitespaceOvertimeFeatureEnabled = launchDarkly.getFlag(WHITESPACE_OVERTIME_CHART_FLAG, false);
});
I have a node module I'm trying to write unit tests for. Here's a part of the module:
function _write(level, message) {
if (level <= _current) {
message = message || "No message provided.";
const consoleFn = consoleFunction[level];
const logFn = console[consoleFn];
logFn(`${levelPrefix[level]}: ${message}`);
}
}
When I run the tests including this one:
test('test writing to error log', () => {
logger.__Rewire__('_write', function (level, message) {
console.error(`ERROR: ${message}`);
});
const spy = jest.spyOn(logger, 'error');
logger.error('error message');
expect(spy).toHaveBeenCalledTimes(1);
});
However after running the tests it still looks like the _write function isn't showing up in the coverage results. Is there a way to get jest to understand all the lines of code are getting exercised? Note that "Uncovered Line #s" refers to the exact line numbers of the _write function. I had hoped that by rewiring the function this would make my coverage 100%.
It looks to me like you are mocking the _write function for that test. I don’t expect those lines to get run in this case.
You could write another test that actually uses the _write function.
I am working on an problem for which i need to detect which test cases fail for any javascript/node.js application, when that application's test suite is run. I need to determine this in a programmatic manner.
Mocha testsuite output result
Consider an example of test output above, for this example I would like to write an external javascript script that can tell me which particular test case failed.
Currently the only solution in my mind is; executing npm test in a javascript child process and read its output from the stdout stream, parse the output and extract necessary information, something like this.
const { spawn } = require('child_process');
const chalk = require('chalk');
const child = spawn('npm.cmd',['test']);
line = 0
child.stdout.on('data', (data) => {
console.log(`${chalk.bgBlue('line = ' + line)} , data = ${data}`);
line++;
});
However, this would be a very strict approach. I would like a more generic way of going about it, that can work for a variety of test modules(not just mocha).
Help would be appreciated !
You can get the state for every test after the execution into the code. So you can know if the test has been passed or not.
The code you need is quite simple. Something like this:
afterEach(function () {
const state = this.currentTest.state;
if (state !== "passed") {
//Do whatever you want with this value
}
});
For example, if you want to store into code, which test has been failed, then you can code this:
var testFailed = []
describe('test', function () {
afterEach(function () {
const state = this.currentTest.state;
if (state !== "passed") {
testFailed.push(this.currentTest.title)
}
});
after(function(){
console.log(testFailed)
})
it('test1', () => {
assert.equal(1, 1)
});
it('test2', () => {
assert.equal(1, 2)
});
})
And the output will be:
test
√ test1
1) test2
[ 'test2' ]
1 passing (15ms)
1 failing
Now you can play with this. You can use the variable to do your work, or even you can create a file or whatever you want to store the info.
I have the following code in Node.js.
const timeout = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
I'm trying to test this code with the following test:
it("Should wait for given time before resolving", async () => {
const MS = 100;
const start = process.hrtime();
await timeout(MS);
const diff = process.hrtime(start);
expect(((diff[0] * NS_PER_SEC) + diff[1]) / 1000000).to.at.least(MS);
});
The problem is sometimes (rarely), this test fails:
Should wait for given time before resolving:
AssertionError: expected 99.595337 to be at least 100
+ expected - actual
-99.595337
+100
Obviously this is some type of timing issue with Node.js or something. If anything I expect await timeout(MS); to take slightly longer than MS. In no case do I expect it to take less time.
What is it about the internals of JavaScript/Node.js that causes this to happen?
This occurred on macOS 10.14.3 running Node.js version 8.15.1.
Sometimes when running a set of mocha tests I don't care about failure details; I only want a list of tests with pass or fail. I've tried several reporters, but they all seem to output details for failures. I like the default spec reporter structure, but I can't find how to hide the details.
Here's an illustrative example. For these tests:
const assert = require('assert')
describe('test test', function() {
it('should pass', function() {
})
it('should fail', function() {
assert(false)
})
})
Which gives output like this:
test test
✓ should pass
1) should fail
1 passing (9ms)
1 failing
1) test test
should fail:
AssertionError [ERR_ASSERTION]: false == true
+ expected - actual
-false
+true
at Context.<anonymous> (test-solution.js:69:5)
but what I want is just this:
test test
✓ should pass
1) should fail
1 passing (9ms)
1 failing
Am I missing something obvious, or are these details just not something I can suppress?
I wanted to hide this too and for me it seems also that most default reporters are not so nice. Each line that is useless will cost us time. In my eyes it should be very simple to customize the output.
Building a own custom reporter is the correct answer to your question. However - as this took me to long - here a very short and easy alternative: Disable the reporter and do some logs on the events.
const Mocha = require('mocha');
let file = './devtest.js';
let passCount = 0;
let errors = [];
// start with disabled reporter
const mocha = new Mocha({ reporter: function () {} });
mocha.addFile(file);
console.log('\n===== start mocha file ' + file);
mocha.run()
.on('pass', function (test) {
passCount++;
logSuccess(test.title);
})
.on('fail', function (test, err) {
errors.push({test, err});
logError(test.title);
})
.on('end', function () {
console.log();
console.log(' -------------------------');
logSuccess(passCount + ' tests passed');
logError(errors.length + ' tests failed');
// do something here - like:
// callback(errors)
});
function logSuccess (str) {
console.log('\u001b[32m ✓ \u001b[0m\u001b[90m' + str + '\u001b[0m');
}
function logError (str) {
console.log('\u001b[31m ✖ ' + str + '\u001b[0m');
}
Of course this has some features less compared to the standard reporter, but extending is pretty simple - you have all the errors and data. So it is very fast.
Perhaps anybody else can post a very simple working example a custom reporter for that - for me the custom reporter broke my console output and I was not interested in more debugging.