Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  20] [ 7]  / answers: 1 / hits: 15397  / 6 Years ago, wed, january 24, 2018, 12:00:00

Here's my callnapply.js file



const callAndApply = {
caller(object, method, nameArg, ageArg, tShirtSizeArg) {
method.call(object, nameArg, ageArg, tShirtSizeArg);
},
applier(object, method, argumentsArr) {
method.apply(object, argumentsArr);
},
};
module.exports = callAndApply;


And here's a snippet from the test file which contains the non-working test:



const callnapply = require('./callnapply');

test('testing Function.prototype.call as mock function', () => {
const outer = jest.fn();
const name = 'Aakash';
const age = 22;
const tee = 'M';
callnapply.caller(this, outer, name, age, tee);
expect(outer.call).toHaveBeenCalledWith(name, age, tee);
});


How do I write the test to check if the method that I am passing is, in fact, being called by the Function.prototype.call function only? I want to check whether .call() is being called and not some other implementation that has been written for the method call.


More From » jestjs

 Answers
66

You can mock the .call() method itself:



const outer = function() {}
outer.call = jest.fn()


Then you can do usual jest mock tests on outer.call.



Here is the working test file:



const callnapply = require('./callnapply');

test('testing Function.prototype.call as mock function', () => {
const outer = function() {};
outer.call = jest.fn();
const name = 'Aakash';
const age = 22;
const tee = 'M';
callnapply.caller(this, outer, name, age, tee);
expect(outer.call).toHaveBeenCalledWith(this, name, age, tee);
});


See this working REPL.


[#55375] Sunday, January 21, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;