Wanted to know the difference b/w .tobeCalled and .tobeCalled().
it('should emit edit as true when confirmation methods is called with true', () =>{
component.confirmation(true)
expect(component.confirmation).toHaveBeenCalled
component.confirmationStatus.subscribe((res: {edit: boolean}) => {
expect(res).toEqual({ edit: true})
})
})
when i use the above block my code is getting covered in coverage.code coverage image for for above code block
when i use the below code block its not getting coverage in the coverage. wanted to understand the difference b/w those code block.
it('should emit edit as true when confirmation methods is called with true', () =>{
const spy = spyOn(component, 'confirmation')
component.confirmation(true)
expect(spy).toHaveBeenCalled()
expect(spy).toHaveBeenCalledWith(true)
component.confirmationStatus.subscribe((res: {edit: boolean}) => {
expect(res).toEqual({ edit: true})
})
})
code coverage image for above code block
Thanks in advance.
Related
I am writing tests for Dark Mode Actions in cypress and I am operating mostly on header. Because of it I am catching it very often using cy.get("header). I am wondering if there is any way to save it in any variable so there is no need to catch it every time and use something like header.contains for example. Documentation of cypress says that simple const header = cy.get("header") doesn't work. Do you know any method to solve this problem so my code will be a little bit cleaner?
Part of test code
it("toggles darkmode", () => {
//when
cy.visit("localhost:3000");
cy.get("header").contains("title", "moon-icon").click({ force: true });
cy.get("header").should("contain", "sun-icon");
cy.get("header").contains("title", "sun-icon").click({ force: true });
cy.get("header").should("contain", "moon-icon");
});
it("remebers dark mode after refresh", () => {
//when
cy.visit("localhost:3000");
cy.get("header").contains("title", "moon-icon").click({ force: true });
cy.reload();
//then
cy.get("header").should("contain", "sun-icon");
});
Assuming all of your tests in this same describe block have the same setup, you could alias the cy.get('header') in a beforeEach.
describe('test', () => {
beforeEach(() => {
cy.visit('localhost:3000');
cy.get('header').as('header');
});
it("toggles darkmode", () => {
//when
cy.get("#header").contains("title", "moon-icon").click({ force: true });
cy.get("#header").should("contain", "sun-icon");
cy.get("#header").contains("title", "sun-icon").click({ force: true });
cy.get("#header").should("contain", "moon-icon");
});
});
Take a look at .within() to set scope of commands.
cy.get("header").within($header => {
cy.contains("title", "moon-icon")
.click()
.should("contain", "sun-icon")
cy.contains("title", "sun-icon")
.click()
.should("contain", "moon-icon")
})
I have a test that requires the value of isBanana to be false.
The test works (and isBanana is false) when I mock the function in the top level index.test.js. However this breaks other tests (as they require isBanana to be true).
jest.mock("myapp-api-functions", () => {
console.log(`executing mock function`);
return {
...jest.requireActual("myapp-api-functions"),
isBanana: false,
};
});
If I move the jest.mock() into the body of the test, isBanana is true and the test doesn't work.
it(`should error when someone tries to use the mock account in production`, async () => {
jest.mock("myapp-api-functions", () => {
console.log(`executing mock function`);
return {
...jest.requireActual("myapp-api-functions"),
isBanana: false,
};
});
...same test function that previously passed...
});
The mock doesn't work and the test fails.
How can I mock the primitive value for a single test?
Calls to jest.mock get hoisted to the top of the code block.
To avoid this behaviour you can instead use jest.doMock e.g.
it(`should error when someone tries to use the mock account in
production`, async () => {
jest.doMock("myapp-api-functions", () => {
console.log(`executing mock function`);
return {
...jest.requireActual("myapp-api-functions"),
isBanana: false,
};
});
// Same test function that previously passed...
});
This will allow you to specify mock behaviour for a specific test.
I have a function which executes some operations in the "accept" call of PrimeNg Confirmation service. I tried to write a Unit test case for it as following:
fit('submit preview config', fakeAsync(() => {
addValues();
component.submitConfig();
component.submitPreviewForm();
fixture.detectChanges();
const confirmationService = TestBed.get(ConfirmationService);
tick(200);
spyOn<any>(confirmationService, 'confirm').and.callFake((params: any) => {
params.accept();
httpMock.expectOne(baseUrl + '/api/project/addOrUpdate').flush(mockSubmitResponse);
expect(component.successMsz).toBe(mockSubmitResponse.message);
});
flush();
}));
The problem is the execution never goes inside callFake. The test case passes but the operation never takes place. Any ideas are welcome.
This is the function I want to test:
submitPreviewForm() {
const messageContent = `<strong>You have updated the following fields:</strong><br/>
<span class="subText" style="font-size: 12px; color: blue;">•${Array.from(this.updatedHighlightedFields).join('<br/> •')}</span>
<br/>
<strong>This will clear JIRA data from DB. Are you sure you want to proceed?</strong>`;
this.confirmationService.confirm({
message: messageContent,
accept: () => {
...
}
});
}
I am using V6 of PrimeNg.
I saw the implementation on this Stack Overflow question:
Angular Unit Test of a PRIME ng confirmation service
Your order of operations seems to be a bit off, you need to spy before calling submitPreviewform.
Try this:
fit('submit preview config', fakeAsync(() => {
const confirmationService = TestBed.get(ConfirmationService); // grab a handle of confirmationService
spyOn<any>(confirmationService, 'confirm').and.callFake((params: any) => {
params.accept();
httpMock.expectOne(baseUrl + '/api/project/addOrUpdate').flush(mockSubmitResponse);
expect(component.successMsz).toBe(mockSubmitResponse.message);
}); // spy on confirmationService.confirm now
addValues();
component.submitConfig();
component.submitPreviewForm();
fixture.detectChanges();
tick(200);
flush();
}));
I'm trying to wrap my head around the following in Jest:
resetAllMocks, resetModules, resetModuleRegistry and restoreAllMocks
and I'm finding it difficult.
I read the jest documentation but it's not too clear. I would appreciate it if someone can please provide me with an example of how the above work and they are different from each other.
The following sections explain the behaviors of each function and its corresponding config directive. In the case of config directives, the explained behavior takes place in between each test making them more and more isolated from the other tests.
References to fn are implying a sample jest mock function under each of these actions.
jest.clearAllMocks() and clearMocks:[boolean]
Resets all the mocks usage data, not their implementation. In other words, it only replaces fn.mock.calls and fn.mock.instances properties of a jest mock function.
jest.resetAllMocks() and the resetMocks:[boolean]
A superset of clearAllMocks() which also takes care of resetting the implementation to a no return function. In other words, it will replace the mock function with a new jest.fn(), not just its fn.mock.calls and fn.mock.instances.
jest.restoreAllMocks() and restoreMocks:[boolean]
Similar to resetAllMocks(), with one very important difference. It restores the original implementation of "spies". So, it goes like "replace mocks with jest.fn(), but replace spies with their original implementation".
So, in cases where we manually assign things with jest.fn() (not spies), we have to take care of implementation restoration ourselves as jest won't be doing it.
jest.resetModules() and resetModules:[boolean]
It resets Jest's module registry which is a cache for all required/imported modules. Jest will re-import any required module after a call to this. Imagine a clean slate without having to deal with all the mocked out modules in other tests.
jest.resetModuleRegistry
It's just an alias for resetModules, see:
https://github.com/facebook/jest/blob/7f69176c/packages/jest-runtime/src/index.ts#L1147
See how clearing, resetting and restoring differ in action:
https://repl.it/#sepehr/jest-mock-api-reset-restore#jest-mock-apis.test.js
PASS ./jest-mock-apis.test.js
jest mock reset/restore api
when calling mockReset() on a test double with custom impl.
if the test double is a spy
✓ jest replaces the impl. to a new undefined-returning jest.fn() (18ms)
if the test double is "not" a spy
✓ jest replaces the impl. to a new undefined-returning jest.fn() (17ms)
when calling mockRestore() on a test double with custom impl.
if the test double is "not" a spy
✓ jest resets the impl. to a new undefined-returning jest.fn() (2ms)
if the test double is a spy
✓ jest restores the original impl. of that spy (7ms)
describe('jest mock reset/restore api', () => {
describe('when calling mockReset() on a test double with custom impl.', () => {
describe('if the test double is a spy', () => {
test('jest replaces the impl. to a new undefined-returning jest.fn()', () => {
const module = { api: () => 'actual' }
jest.spyOn(module, 'api').mockImplementation(() => 'spy mocked')
expect(module.api()).toStrictEqual('spy mocked')
expect(module.api).toHaveBeenCalledTimes(1)
module.api.mockReset()
expect(module.api()).toStrictEqual(undefined)
expect(module.api).toHaveBeenCalledTimes(1)
})
})
describe('if the test double is "not" a spy', () => {
test('jest replaces the impl. to a new undefined-returning jest.fn()', () => {
const api = jest.fn(() => 'non-spy mocked')
expect(api()).toStrictEqual('non-spy mocked')
expect(api).toHaveBeenCalledTimes(1)
api.mockReset()
expect(api()).toStrictEqual(undefined)
expect(api).toHaveBeenCalledTimes(1)
})
})
})
describe('when calling mockRestore() on a test double with custom impl.', () => {
describe('if the test double is "not" a spy', () => {
test('jest resets the impl. to a new undefined-returning jest.fn()', () => {
const api = jest.fn(() => 'non-spy mocked')
expect(api()).toStrictEqual('non-spy mocked')
expect(api).toHaveBeenCalledTimes(1)
api.mockRestore()
expect(api()).toStrictEqual(undefined)
expect(api).toHaveBeenCalledTimes(1)
})
})
describe('if the test double is a spy', () => {
test('jest restores the original impl. of that spy', () => {
const module = { api: () => 'actual' }
jest.spyOn(module, 'api').mockImplementation(() => 'spy mocked')
expect(module.api()).toStrictEqual('spy mocked')
expect(module.api).toHaveBeenCalledTimes(1)
module.api.mockRestore()
expect(module.api()).toStrictEqual('actual')
expect(module.api).not.toHaveProperty('mock')
})
})
})
})
Thanks for #sepehr answer.
I think it would be easier to understand by example.
Quick tips:
If you want to test mock function called times, clear before you use
If you want to make sure mock return value wouldn't pollute other test case, call reset
If you want to use origin method instead of mock implementation, call restore.
import {Calculator} from './calculator';
describe('calculator add', function () {
let calculator = new Calculator();
const mockAdd = jest.spyOn(calculator, 'add');
it('mock the add method', function () {
calculator.add = mockAdd.mockReturnValue(5);
expect(calculator.add(1, 2)).toBe(5);
});
it('because we didnt clear mock, the call times is 2', function () {
expect(calculator.add(1, 2)).toBe(5);
expect(mockAdd).toHaveBeenCalledTimes(2);
});
it('After clear, now call times should be 1', function () {
jest.clearAllMocks();
expect(calculator.add(1, 2)).toBe(5);
expect(mockAdd).toHaveBeenCalledTimes(1);
});
it('we reset mock, it means the mock has no return. The value would be undefined', function () {
jest.resetAllMocks();
expect(calculator.add(1, 2)).toBe(undefined);
});
it('we restore the mock to original method, so it should work as normal add.', function () {
jest.restoreAllMocks();
expect(calculator.add(1, 2)).toBe(3);
});
});
I am trying to spy on $.ajax in Jasmine 2.0 tests. Here is a simplified example (TypeScript) showing my scenario:
describe("first test", () => {
var deferred = jQuery.Deferred();
spyOn($, "ajax").and.callFake((uri: string, settings: JQueryAjaxSettings) => {
return deferred.resolve("ThisIsADummyResult");
});
it("should return dummy result", done => {
$.ajax("http://somedummyserver.net").then(result => {
expect(result).toBe("ThisIsADummyResult");
done();
});
});
});
describe("second test", () => {
var deferred = jQuery.Deferred();
spyOn($, "ajax").and.callFake((uri: string, settings: JQueryAjaxSettings) => {
return deferred.resolve("ThisIsAnotherResult");
});
it("should return another result", done => {
$.ajax("http://somedummyserver.net").then(result => {
expect(result).toBe("ThisIsAnotherResult");
done();
});
});
});
firstTest as well as second test work if I run them alone. However, if I run both tests as shown above, I get the following error message: ajax has already been spied upon.
So my questions are:
Shouldn't the spies be reset by Jasmine after each test automatically? Why doesn't that work in my case?
Is there another way of using spyOn which makes Jasmine reset the spies?
How can I manually reset the spies?
Update: I continued experimenting and found a possible solution myself. If I set up the spies inside of the it spec, both tests run fine. Here is the code for first test showing what I mean:
describe("first test", () => {
it("should return dummy result", done => {
var deferred = jQuery.Deferred();
spyOn($, "ajax").and.callFake((uri: string, settings: JQueryAjaxSettings) => {
return deferred.resolve("ThisIsADummyResult");
});
$.ajax("http://somedummyserver.net").then(result => {
expect(result).toBe("ThisIsADummyResult");
done();
});
});
});
Still, it would be very interesting why the first version does not work. Why does Jasmine not reset the spies in the first version whereas it does in the second one?
For stuff that is used across all tests but you need it reset for each test use 'beforeEach' : http://jasmine.github.io/2.0/introduction.html#section-Setup_and_Teardown
Jasmine does not magically know which lines of your describe body you want reevaluated for each 'it' block.