How i can write fromEvent(window, 'scroll')unit test using sinon js, mocha & chai for the next method? - sinon-chai

addScroll(): void {
fromEvent(this.$size, 'scroll')
.pipe(takeUntil(this.unSubs$))
.subscribe({
next: () => this.scroll = this.$size.pageYOffset > 5
});
}

Related

Jest SpyOn __mocks__ module

We mock our modules using __mocks__. I'd like to spyOn a module function in my test but it doesn't seem to be working. Related question, I'd also like to override a mocked module function for a test (ie throw an exception). How can I do this?
├──__mocks__
| └──DB-Utils.js
| └──controllers
| └──myController.js
├──node_modules
__mocks__/DB-Utils.js:
const { MyController } = require('./controllers/myController');
module.exports = {
MyController,
};
__mocks__/controllers/myController.js:
class MyController {
async setAvailability(id, availability) {
return true;
}
}
module.exports = {
MyController,
};
test.spec.js:
const { MyController } = require('DB-Utils');
const myController = new MyController();
describe('Register Tests', () => {
fit('myController setAvailability', async () => {
---code that calls a class that ends up calling myController.setAvailability---
expect(myController.setAvailability).toHaveBeenCalledWith('foo', 'bar');
});
});
My tests pass in that the mock myController is called, however it fails the toHaveBeenCalledWith with an error of Number of calls: 0
How can I spy setAvailability?
For the related question I'd also like to be able to do something like the following:
describe('Register Tests', () => {
fit('myController setAvailability throws', async () => {
jest.spyOn(myController, 'setAvailability').mockImplementation(() => {
throw new Error()
});
expect(---code that calls a class that ends up calling myController.setAvailability---).toThrow();
});
});

Sinon stub replaces class property for whole test file instead of describe block

I'm trying to replace a static method of a class so that it returns custom value for testing purposes.
I have multiple test (describe) blocks in my file, and my goal is to replace the static method only in one of the describe blocks.
The problem is that the method is replaced for all the tests, even though I have a teardown method that is replacing the static method with the original method.
Some code:
class Cat {
static sound() {
return "Meow";
}
}
module.exports = {
Cat
}
const sinon = require("sinon");
const { Cat } = require("./myClass");
describe("Main tests", () => {
describe("Test Cat", () => {
it("Meows", () => {
expect(Cat.sound()).toBe("Meow")
})
})
describe("Test Dog", () => {
const stub = sinon
.stub(Cat, "sound")
.callsFake(() => "Woof");
afterAll(() => {
stub.restore();
});
it("Barks", () => {
expect(Cat.sound()).toBe("Woof")
})
})
})
Test results - the unreplaced test case is failing:
FAIL ./index.test.js
Main tests
Test Cat
✕ Meows (6ms)
Test Dog
✓ Barks
● Main tests › Test Cat › Meows
expect(received).toBe(expected) // Object.is equality
Expected: "Meow"
Received: "Woof"
7 | describe("Test Cat", () => {
8 | it("Meows", () => {
> 9 | expect(Cat.sound()).toBe("Meow")
| ^
10 | })
11 | })
12 |
Is there a way how to prevent this?
I tried using createSandbox:
const sandbox = sinon.createSandbox()
const stub = sandbox
.stub(Cat, "sound") // etc
but it's the same thing.
Any help would be appreciated.
This task can be done easily with jestjs only (without sinon).
Just use jest.spyOb function to spy sound function, and you can mock the result of this function:
const { Cat } = require('./myClass');
describe('Main tests', () => {
beforeEach(() => {
jest.spyOn(Cat, 'sound');
});
afterEach(() => {
jest.resetAllMocks();
});
describe('Test Cat', () => {
it('Meows', () => {
// Don't mock, just call actual logic
expect(Cat.sound()).toBe('Meow');
});
});
describe('Test Dog', () => {
it('Barks', () => {
Cat.sound.mockReturnValue('Woof'); // mock return value of `sound()`
expect(Cat.sound()).toBe('Woof');
});
});
});

How to cover arrow functions in unit testing in angular?

this.service = () => { -- statements -- }
The above statement is to be tested using jasmine unit testing in angular.
Can i get some suggestions for that ?
it("should service call",()=>{ // i want to call the arrow function here like component.service.? what to use in place of '?'. })
It is a function so you call it immediately:
example:
interface Service {
fun: () => string;
}
class Component {
constructor() {
this.service = () => {
return {
fun: () => 'hello'
};
};
}
service: () => Service;
}
Calling it:
const component = new Component();
const service = component.service();
const message = service.fun();
// or in one line:
const message = new Component().service().fun();
Typescript playground example

How to test a function in React Component with Jest + Enzyme?

I am using the testing-library/jest-dom + Enzyme to do the unit testing.and here I need to test a funtion inside a React function.
import React, { useEffect } from 'react';
function Component1() {
useEffect( async () => {
fetchSomeData();
}, [])
const fetchSomeData = async () =>{
console.log('fetchSomeData')
}
return <div>Component1</div>;
}
export default Component1;
and my test file:
Enzyme.configure({adapter:new Adapter()})
describe('Name of the group', () => {
it('should ', () => {
const wrapper = shallow( <Component1/>)
expect(wrapper.exists());
});
});
in fact I don't need to test the correctness , I just need the code be covered in jest. but whatever I tried , it seems not covered by jest:

How to test setInterval on a method?

I have a class
class Dummy {
constructor() {
this.prop1 = null;
this.prop2 = null;
this.prop3 = setInterval(() => {
this.method1()
}, 1000);
}
method1() {
// Method logic
}
}
var dummyObject = new Dummy();
module.exports = dummyObject;
I'd like to write tests to verify that method1 is being invoked after every 1s.
Following is the test code
const dummyObject = require('./dummy.js');
describe("Test setInterval", function () {
it("Test setInterval", function () {
const clock = sinon.useFakeTimers();
const spy = sinon.spy(dummyObject, 'method1');
clock.tick(1001);
expect(spy.calledOnce).to.be.true;
clock.restore();
})
})
When I run the tests however, I get an error 'Expected false to equal to true' and on further digging I realized I am not able to spy on the method which is being called via setInterval.
Please share any thoughts on what I can do to test this scenario?
This is not going to work the way you want it to, because the method (method1) is already called when you require the module and hence there is no chance to spy it afterwards in your test.
I recommend to refactor your Module to export the class, not the instance like:
module.exports = class Dummy {
constructor() {
this.prop1 = null;
this.prop2 = null;
this.prop3 = setInterval(() => {
this.method1()
}, 1000);
}
method1() {
// Method logic
}
}
Then in you test, require the class and spy on the method before you instantiate it:
const sinon = require('sinon');
const Dummy = require('./dummy.js');
describe("Test setInterval", function () {
it("Test setInterval", function () {
const clock = sinon.useFakeTimers();
// Spy on the method using the class' prototype
const spy = sinon.spy(Dummy.prototype, 'method1');
// Initialize the class and make sure its `constructor` is called after you spied on the method
new Dummy();
clock.tick(1001);
expect(spy.calledOnce).to.be.true;
clock.restore();
})
})

Resources