Issue with setting up jest mock - javascript

I have the following function that is used within cypress tests for which I want to do unit testing (filterTests.js):
const filterTests = (definedTags, runTest) => {
console.log(`Cypress tags: ${definedTags}`);
let isFound = true;
const includeTag = Cypress.env('INCLUDETAG');
const excludeTag = Cypress.env('EXCLUDETAG');
if (includeTag) {
isFound = definedTags.includes(includeTag);
}
if (excludeTag) {
isFound = ! definedTags.includes(excludeTag);
}
if (isFound) {
runTest();
}
};
export default filterTests;
A test double for Cypress.env needs to be created. I'm not sure if this would technically be considered a stub, mock, fake, dummy, etc..., but the philosophical discussion isn't the focus right now. It looks like in the Cypress world, everything is lumped together under 'mock'.
I started down the path of something like this in the Jest test file:
import filterTests from '../../cypress/support/filterTests';
describe('Something', () => {
jest.mock('Cypress', () => ({
env: {
INCLUDETAG: 'jenkins1'
}
}));
it('Something else ', (done) => {
const tempFunc = () => {
console.log('here a');
done();
};
filterTests(tag, tempFunc);
});
});
But for that I get the error message:
Cannot find module 'Cypress' from 'spec/cypress/filterTestsSO2.test.js'
2 |
3 | describe('Something', () => {
> 4 | jest.mock('Cypress', () => ({
| ^
5 | env: {
6 | INCLUDETAG: 'jenkins1'
7 | }
I believe what is complicating this situation is that Cypress is not explicitly imported in filterTests.js

I think you might just want to set the env value at the top of the test
describe('Something', () => {
Cypress.env(INCLUDETAG, 'jenkins1')
it('Something else ', (done) => {
const tempFunc = () => {
console.log('here a');
done();
};
filterTests(tag, tempFunc); // this function will read the env set above
})
})
Further info - Cypress has a cy.spy() which wraps a method and records it's calls but otherwise leaves it's result the same.
Also cy.stub() which records calls but also provides a fake result.
Jest globals
If you are running the test in Jest, then the Cypress global should be able to be mocked simply by setting it up
global.Cypress = {
env: () => 'jenkins1' // or more complicated fn as test requires
}
Note I expect this will only work with simple cases. Cypress wraps jQuery, Chai and Mocha so they behave slightly differently when a Cypress test runs. If the function you test uses any of those features, even implicitly (like command retry), then Jest will not reproduce the right environment.
My recommendation, test Cypress with Cypress.

Related

Jasmine test case are failing, when testing setTimeout inside function [duplicate]

This question already has an answer here:
How to test code setup with babel configuration(For Library) using Jasmine?
(1 answer)
Closed 1 year ago.
Good Day Everyone,
I am quite new to testing frameworks Jasmine. We have a TS project setup and I am trying to test a function consisting of setTimeout, but it keeps failing. I am trying to use Clock
One Important point I noticed is that I am using babel-loader as soon as I change the webpack configuration to ts-loader. The test case doesn't fail. (Don't know Why 🤷‍♀️). I have checked multiple times but no luck.
UPDATE
I figured out why the test cases are failing but I have no idea why is it happening.
The configurations of babel and ts-loader are correct I just changed the setTimeout to window.setTimeout(in babel-loader) repository and now the test cases are executing successfully🤷‍♀️. This was just a wild guess from Stack Overflow Link.
I added a console statement of setTimeout and window.setTimeout and found that the definitions of both functions are very different. window.setTimeout has a definition(Green circle in the screenshot) that is the same as after we install Jasmine.clock install. ie. HERE
But setTimeout definition(Red circle in the screenshot) is very different(below).
function (/* ...args */) {
return fn.apply(that, arguments);
}
I tried doing the same in ts-loader repository but here setTimeout and window.setTimeout definitions are the same.
Code:
hideToast() {
setTimeout(() => {
this.showToast = false;
}, 5000);
}
Test Spec:
beforeEach(() => {
// Sometimes calling install() will fail for some reason,
// but calling uninstall() first will make it work
jasmine.clock().uninstall();
jasmine.clock().install();
});
afterEach(() => {
jasmine.clock().uninstall();
});
it('should hide toast', () => {
const obj: Car = new Car();
obj.showToast = true; // This value should change after timeout
obj.hideToast(); // Call the component method that turns the showToast value as false
jasmine.clock().tick(5000);
expect(obj.showToast).toBeFalsy(); // Then executes this
});
Any suggestion would be helpful.
With babel-loader(Test case fail's) Screenshot(Branch = "main"):
https://github.com/dollysingh3192/ts-babel-template
With ts-loader(Test cases passed) Screenshot(Branch = "tsloader"):
https://github.com/dollysingh3192/ts-babel-template/tree/tsloader
Example with clock() using a promise that we resolve straight away:
import { Car } from './car';
describe('Car', () => {
beforeEach(() => {
jasmine.clock().uninstall(); // you probably don't need this line
jasmine.clock().install();
});
afterEach(() => {
jasmine.clock().uninstall();
});
it('should hide toast', () => {
const obj: Car = new Car();
obj.showToast = true; // also here, it's redundant, as set to true in constructor
obj.hideToast();
Promise.resolve().then(() => {
jasmine.clock().tick(5000);
expect(obj.showToast).toBeFalsy();
});
});
});
Other ideas on how to do it in this github issue
But let's forget about the simple (and best solution) for a moment and dig a big into the issue. Without the Clock class, we would have to use the done() callback.
In that case, we would have two solutions:
1 - change jasmine.DEFAULT_TIMEOUT_INTERVAL, to be at least 1ms higher than your timeout:
import { Car } from './car';
describe('Car', () => {
beforeEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 5001;
});
it('should hide toast', (done) => {
const obj: Car = new Car();
obj.hideToast();
setTimeout(() => {
expect(obj.showToast).toBeFalsy();
done();
}, 5000)
});
});
This works with the done() callback (that might be used while working with async tasks)
and by overriding the jasmine.DEFAULT_TIMEOUT_INTERVAL.
2 - Lower your timeout - by 1 millisecond (yes, 1ms is enough):
import {Car} from './car';
describe('Car', () => {
it('go() works', () => {
const car: Car = new Car();
const returnValue = car.go('vroom');
expect(returnValue).toEqual('vroom');
});
it('should hide toast', (done) => {
const obj: Car = new Car();
obj.hideToast();
setTimeout(() => {
expect(obj.showToast).toEqual(false);
done();
}, 4999);
});
});
Same as before, done callback, but this time we finish 1 millisecond before the Jasmine default timeout and the test will pass (obviously, we need to do it in the class and in the test).
According to the Jasmine docs:

How to mock module in different ways in different tests in the same test file in Jest?

Currently I have this:
jest.mock('my/hook', () => () => false)
I want my custom React hook module to return false in every test by default, but in a few tests I want it to return true.
The hook is implemented essentially like this:
function useMyHook(key) {
switch (key) {
case 'foo':
case 'bar':
return true
default:
return false
}
}
I am using the hook several times in my component, once for the foo key and once for the bar key. I want it to return false for both keys by default.
But for a few tests I want the foo key to return true, and for other tests I want the bar key to return true.
I tried that by doing this in the specific test, but it didn't do anything:
it('should do x', () => {
jest.doMock('my/hook', () => (key) => {
if (key == 'foo') {
return true
}
})
// ... rest of test
})
How do I customize module mocks on a per-test basis in Jest?
jest.doMock alone can't do anything because a module that depends on it has been already imported earlier. It should be re-imported after that, with module cache discarded with either jest.resetModules or jest.isolateModules:
beforeEach(() => {
jest.resetModules();
});
it('should do x', () => {
jest.doMock('my/hook', ...)
require('module that depends on hook');
// ... rest of test
})
Since it's a function that needs to be mocked differently, a better way is to mock the implementation with Jest spies instead of plain functions:
jest.mock('my/hook', () => jest.fn(() => false))
...
it('should do x', () => {
hook.mockReturnValueOnce(true);
// ... rest of test
})

Display test file name in Mocha output

Is there anyway to have mocha display the name of, or group the output by the test file?
Given two test files, ./test/testFoo.js and ./test/testBar.js I'd like to see something like this when running mocha test:
* testFoo:
Doing X
✓ should return A
✓ even with negative input
Doing Y
✓ should return B
✓ should return C when called with Egyptian hieroglyphs
* testBar:
Doing Z
✓ should return D
(This might be an XY problem. If there are other way to group tests in two levels, I'm just as interested. It's just that the files are already there, as a kind of natural first level group.)
I got tired of there being no solution for this every time I went searching for one and built my own reporter:
https://www.npmjs.com/package/mocha-spec-reporter-with-file-names
That page contains the details but here they are repeated:
install it: npm i -D mocha-spec-reporter-with-file-names
set it at your reporter
cli: npx mocha --reporter './node_modules/mocha-spec-reporter-with-file-names'
config:
// .mocharc.js
const SpecReporterWithFileNames = require('mocha-spec-reporter-with-file-names');
module.exports = {
reporter: SpecReporterWithFileNames.pathToThisReporter,
};
Output currently looks like this:
You should be good using Mocha's describe method to logically group your tests. For the output you desire, the structure of your tests would look like:
/test/testFoo.js
describe('testFoo', () => {
describe('Doing X', () => {
it('should return A', () => {
});
it('even with negative input', () => {
});
});
describe('Doing Y', () => {
it('should return B', () => {
});
it('should return C when called with Egyptian hieroglyphs', () => {
});
});
});
/test/testBar.js
describe('testBar', () => {
describe('Doing Z', () => {
it('should return D', () => {
});
});
});

Spying on a non-exported node.js function using jest not working as expected

I am trying to mock a non-exported function via 'jest' and 're-wire'.
Here I am trying to mock 'iAmBatman' (no-pun-intended) but it is not exported.
So I use rewire, which does it job well.
But jest.mock doesn't work as expected.
Am I missing something here or Is there an easy way to achieve the same ?
The error message given by jest is :
Cannot spy the property because it is not a function; undefined given instead
service.js
function iAmBatman() {
return "Its not who I am underneath";
}
function makeACall() {
service.someServiceCall(req => {
iAmBatman();
});
return "response";
}
module.export = {
makeACall : makeACall;
}
jest.js
const services = require('./service');
const rewire = require('rewire');
const app = rewire('./service');
const generateDeepVoice = app.__get__('iAmBatman');
const mockDeepVoice = jest.spyOn(services, generateDeepVoice);
mockDeepVoice.mockImplementation(_ => {
return "But what I do that defines me";
});
describe(`....', () => {
test('....', done => {
services.makeACall(response, () => {
});
});
})
It is not entirely clear what your goal is, but if you look at the documentation of jest.spyOn, you see that it takes a methodName as the second argument, not the method itself:
jest.spyOn(object, methodName)
This explains your error: you didn't give the function name, but the function itself.
In this case, using jest.spyOn(services, 'iAmBatman') wouldn't work, since iAmBatman is not exported, and therefore services.iAmBatman is not defined.
Luckily, you don't need spyOn, as you can simply make a new mock function, and then inject that with rewire's __set__ as follows:
(note that I deleted the undefined service.someServiceCall in your first file, and fixed some typos and redundant imports)
// service.js
function iAmBatman() {
return "Its not who I am underneath";
}
function makeACall() {
return iAmBatman();
}
module.exports = {
makeACall: makeACall
}
// service.test.js
const rewire = require('rewire');
const service = rewire('./service.js');
const mockDeepVoice = jest.fn(() => "But what I do that defines me")
service.__set__('iAmBatman', mockDeepVoice)
describe('service.js', () => {
test('makeACall should call iAmBatman', () => {
service.makeACall();
expect(mockDeepVoice).toHaveBeenCalled();
});
})
Another option would be to restructure your code with iAmBatman in a seperate module, and then mock the module import with Jest. See documentation of jest.mock.

Mocking globals in Jest

Is there any way in Jest to mock global objects, such as navigator, or Image*? I've pretty much given up on this, and left it up to a series of mockable utility methods. For example:
// Utils.js
export isOnline() {
return navigator.onLine;
}
Testing this tiny function is simple, but crufty and not deterministic at all. I can get 75% of the way there, but this is about as far as I can go:
// Utils.test.js
it('knows if it is online', () => {
const { isOnline } = require('path/to/Utils');
expect(() => isOnline()).not.toThrow();
expect(typeof isOnline()).toBe('boolean');
});
On the other hand, if I am okay with this indirection, I can now access navigator via these utilities:
// Foo.js
import { isOnline } from './Utils';
export default class Foo {
doSomethingOnline() {
if (!isOnline()) throw new Error('Not online');
/* More implementation */
}
}
...and deterministically test like this...
// Foo.test.js
it('throws when offline', () => {
const Utils = require('../services/Utils');
Utils.isOnline = jest.fn(() => isOnline);
const Foo = require('../path/to/Foo').default;
let foo = new Foo();
// User is offline -- should fail
let isOnline = false;
expect(() => foo.doSomethingOnline()).toThrow();
// User is online -- should be okay
isOnline = true;
expect(() => foo.doSomethingOnline()).not.toThrow();
});
Out of all the testing frameworks I've used, Jest feels like the most complete solution, but any time I write awkward code just to make it testable, I feel like my testing tools are letting me down.
Is this the only solution or do I need to add Rewire?
*Don't smirk. Image is fantastic for pinging a remote network resource.
As every test suite run its own environment, you can mock globals by just overwriting them. All global variables can be accessed by the global namespace:
global.navigator = {
onLine: true
}
The overwrite has only effects in your current test and will not effect others. This also a good way to handle Math.random or Date.now.
Note, that through some changes in jsdom it could be possible that you have to mock globals like this:
Object.defineProperty(globalObject, key, { value, writable: true });
The correct way of doing this is to use spyOn. The other answers here, even though they work, don't consider cleanup and pollute the global scope.
// beforeAll
jest
.spyOn(window, 'navigator', 'get')
.mockImplementation(() => { ... })
// afterAll
jest.restoreAllMocks();
Jest may have changed since the accepted answer was written, but Jest does not appear to reset your global after testing. Please see the testcases attached.
https://repl.it/repls/DecentPlushDeals
As far as I know, the only way around this is with an afterEach() or afterAll() to clean up your assignments to global.
let originalGlobal = global;
afterEach(() => {
delete global.x;
})
describe('Scope 1', () => {
it('should assign globals locally', () => {
global.x = "tomato";
expect(global.x).toBeTruthy()
});
});
describe('Scope 2', () => {
it('should not remember globals in subsequent test cases', () => {
expect(global.x).toBeFalsy();
})
});
If someone needs to mock a global with static properties then my example should help:
beforeAll(() => {
global.EventSource = jest.fn(() => ({
readyState: 0,
close: jest.fn()
}))
global.EventSource.CONNECTING = 0
global.EventSource.OPEN = 1
global.EventSource.CLOSED = 2
})
If you are using react-testing-library and you use the cleanup method provided by the library, it will remove all global declarations made in that file once all tests in the file have run. This will then not carry over to any other tests run.
Example:
import { cleanup } from 'react-testing-library'
afterEach(cleanup)
global.getSelection = () => {
}
describe('test', () => {
expect(true).toBeTruthy()
})
If you need to assign and reassign the value of a property on window.navigator then you'll need to:
Declare a non-constant variable
Return it from the global/window object
Change the value of that original variable (by reference)
This will prevent errors when trying to reassign the value on window.navigator because these are mostly read-only.
let mockUserAgent = "";
beforeAll(() => {
Object.defineProperty(global.navigator, "userAgent", {
get() {
return mockUserAgent;
},
});
});
it("returns the newly set attribute", () => {
mockUserAgent = "secret-agent";
expect(window.navigator.userAgent).toEqual("secret-agent");
});

Categories