Enzyme restore getEelemenById before each test - javascript

I stub getElementById in beforeEach, and want to restore it before another test and stub again with anothter returns value. Because now I recieve error
TypeError: Attempted to wrap getElementById which is already wrapped
let loginUrl = 'loginUrl'
const url = '/app/auth'
const textContent = `{"${loginUrl}":"${url}"}`
let htmlDecode
describe('identityServer', () => {
beforeEach(() => {
htmlDecode = sinon.stub().returns(textContent)
sinon.stub(document, 'getElementById').returns({textContent})
sinon.stub(htmlEncoder, 'Encoder').returns({htmlDecode: () => htmlDecode})
identityServerModel()
})
it('should return correct model for IdentityServer', () => {
window.identityServer.getModel().should.deep.equal({[loginUrl]: url})
})
})
describe('identityServer', () => {
beforeEach(() => {
htmlDecode = sinon.stub().returns(textContent)
sinon.stub(document, 'getElementById').returns({innerHTML: textContent})
sinon.stub(htmlEncoder, 'Encoder').returns({htmlDecode: () => htmlDecode})
identityServerModel()
})
it('should return correct model using serialization HTML from innerHTML property when textContent is undefined', () => {
window.identityServer.getModel().should.deep.equal({[loginUrl]: url})
})
})

Try add:
afterEach(() => {
document.getElementById.restore();
})
into every describe(...).

Related

testing module functions with jest

I have a module that looks like this:
const config = require('config')
const isActive = config.get('isActive')
const infoMap = new Map()
const set = (key, value) => {
infoMap.set(key, value)
}
const get = (key) => infoMap.get(key)
module.exports={set, get}
and a test where I test the stuff:
let get
let set
beforeEach(() => {
jest.mock('config')
mockIsActive = require('config').get.mockReturnValueOnce(true)
get = require('../cache/mymap').get
set = require('../cache/mymap').set
})
describe('The map', () => {
describe('when data is added', () => {
set('testKey', "testData")
it('should contains the data', async () => {
const dataFromMap = get('testKey')
assert("testData", dataFromMap)
})
})
})
It fails when the set is called with:
set is not a function
Strange is that get works without problems.
You must call the set function inside the it function, otherwise it is not yet defined:
describe('when data is added', () => {
it('should contains the data', async () => {
set('testKey', "testData")
const dataFromMap = get('testKey')
assert("testData", dataFromMap)
})
})
beforeEach runs before each it function, not before describe. This is also why get does work in your example - it is inside the it function.

how to check function is called or not in react js?

I am trying to test my service which have one function saveWithoutSubmit
export const saveWithoutSubmit = async (
values,
orderId,
taskId,
fseMsisdn,
updateTaskListAfterFilter
) => {
var obj = {
remarks: values.remarks,
requestedBy: localStorage.getItem("msisdn")
};
try {
const response = await sendPostRequest(`${API_TASK_URL}closeSr`, {
...obj,
saveWithoutSubmit: true
});
if (response && response.data && response.data.status.code !== "200") {
error(response.data.result.message);
} else {
console.log(response);
success(response.data.status.message);
updateTaskListAfterFilter();
}
} catch (e) {
if (e.response && e.response.data) {
console.log(e.response.data.message);
error(e.response.data.status.message);
}
}
};
I want to check success or error method is called or not ? or updateTaskListAfterFilter is called or not?
I tried like this
https://codesandbox.io/s/ecstatic-currying-5q1b8
describe("remark service test", () => {
const fakeAxios = {
get: jest.fn(() => Promise.resolve({ data: { greeting: "hello there" } }))
};
it("save without sumit", () => {
const updateTaskListAfterFilter = () => {};
saveWithoutSubmit({}, updateTaskListAfterFilter);
expect(updateTaskListAfterFilter).toBeCalled();
});
});
can you please suggest how i will test async methods or post request (using mook data)??
so that my test cases will be passed.
I want to check if I got success from promise my success method will be called else error
any update ?..!!
update
https://codesandbox.io/s/ecstatic-currying-5q1b8
it("save without sumit", async () => {
const sendPostRequest = jest.fn(() =>
Promise.resolve({ data: { greeting: "hello there" } })
);
const updateTaskListAfterFilter = () => {};
saveWithoutSubmit({}, updateTaskListAfterFilter);
expect(updateTaskListAfterFilter).toBeCalled();
});
it("save without sumit", async () => {
const sendPostRequest = jest.fn(() =>
Promise.resolve({ data: { greeting: "hello there" } })
);
const mockUpdateTaskListAfterFilter = jest.fn();
const updateTaskListAfterFilter = () => {};
saveWithoutSubmit({}, updateTaskListAfterFilter);
expect(updateTaskListAfterFilter).toBeCalled();
await wait(() => {
expect(mockUpdateTaskListAfterFilter).toBeCalled();
});
});
You should change it("save without sumit", () => { to it("save without sumit", async () => {.
Then you usually use jest.fn() to create a mock function that you will give to another function or component.
Finally, await the mock function to be called:
await wait(() => {
expect(mockUpdateTaskListAfterFilter).toBeCalled();
});
Alternatively, you can await some other event that you know will occur before your mock is called, like some other mock getting called or something appearing on the page, and then check that your mock was called.

Is there a better way to define a variable in a Mocha 'before' call?

I want to set up a request once and then use it in multiple tests. This was the best way I could come up to do that, but it seems odd to have to have to declare req mutable just so it will be available in an outside scope.
describe('GET /password', () => {
let req
before(() => {
req = chai.request(app).get('/password')
return req
})
it('should get the password page', () => {
return req.then(res => res.should.have.status(200))
})
describe('The password page', () => {
it('should render HTML', () => {
return req.then(res => res.should.be.html)
})
})
})
I was hoping I could do something like
const req = before(() => {
return chai.request(app).get('password')
})
... but it seems that before() does not return the value returned in its callback.
Is there a better (more "elegant") way to do this?
You can simply use a function returning a promise:
describe('GET /password', () => {
function getPassword () {
return chai.request(app).get('/password')
}
it('should get the password page', () => {
return getPassword()
.then(res => res.should.have.status(200))
.catch(err => err.should.not.exist)
})
describe('The password page', () => {
it('should render HTML', () => {
return getPassword()
.then(res => res.should.be.html)
.catch(err => err.should.not.exist)
})
})
})
I find using a function also much more readable than using before which is not visible at first look.
In my previous experience, I usually stored the response in a variable then in each test, I accessed that variable. Seems that your case is only care about response so this solution below may fit.
describe('GET /password', () => {
let response; // create a variable
before(() => {
return chai.request(app).get('/password') // add `return` here for promise
.then(res => {
response = res; // store response from api to the variable
})
})
it('should get the password page', () => {
response.should.have.status(200);
})
describe('The password page', () => {
it('should render HTML', () => {
response.should.be.html
})
})
})
Having the variable as mutable is not odd in my opinion.
Hope it helps

Failed toHaveBeenCalled() jest test in Vue component

Not working function call with 'click' trigger in test.
I called function - it is working
I triggered click but test was failed.
describe("Message.test.js", () => {
let wrapper;
const createWrapper = propsData => mount(Message, { propsData
describe("Events", () => {
beforeEach(() => {
wrapper = createWrapper({ message: "Cat" });
});
//Working
it("calls handleClick", () => {
const spy = jest.spyOn(wrapper.vm, 'handleClick');
wrapper.vm.handleClick();
expect(spy).toHaveBeenCalled();
});
//NOT WORKING. WHY?
it("calls handleClick when click on message", () => {
wrapper.vm.handleClick = jest.fn();
//It is Ok
expect(wrapper.contains('.message')).toBe(true);
// #click="handleClick" on element
wrapper.find('.message').trigger('click');
expect(wrapper.vm.handleClick).toHaveBeenCalledTimes(1);
})
});
I added console.log to the function. During the test, I see what function was called.
it('calls handleClick when click on message', () => {
const handleClick = jest.fn()
wrapper.setMethods({ handleClick })
const el = wrapper.find('.message').trigger('click')
expect(handleClick).toBeCalled()
})
// stub
it('triggers a message-clicked event when a handleClick method is called', () => {
const stub = jest.fn()
wrapper.vm.$on('message-clicked', stub)
wrapper.vm.handleClick()
expect(stub).toBeCalledWith('Cat')
})

Scoping in Jest when mocking functions

I have a test where I'm trying to mock a component in two different situations. When I use jest.fn. It almost looks like the first test is just taking the value from the second.
describe('tests', () => {
let sampleArray = new Array()
Array.prototype.test = function() {
return this.innerArray()
}
describe('empty', () => {
sampleArray.innerArray = jest.fn(() => [])
it('testArray is empty', () => {
expect(sampleArray.test().length).toEqual(0)
})
})
describe('not empty', () => {
sampleArray.innerArray = jest.fn(() => ['test'])
it('testArray is not empty', () => {
console.log(sampleArray.innerArray())
expect(sampleArray.test().length).toEqual(1)
})
})
})
When I console.log I get the array I expect from innerArray, but it just looks like it doesn't use it.
FAIL test/sample.test.js
tests
empty
✕ testArray is empty (8ms)
not empty
✓ testArray is not empty (4ms)
● tests › empty › testArray is empty
expect(received).toEqual(expected)
Expected value to equal:
0
Received:
1
edit: If I place it inside the it scope, it works. But why can't I do it in the describe scope?
describe('tests', () => {
let sampleArray = new Array()
Array.prototype.test = function() {
return this.innerArray()
}
describe('empty', () => {
it('testArray is empty', () => {
sampleArray.innerArray = jest.fn(() => [])
console.log(sampleArray.innerArray())
expect(sampleArray.test().length).toEqual(0)
})
})
describe('not empty', () => {
it('testArray is not empty', () => {
sampleArray.innerArray = jest.fn(() => ['test'])
expect(sampleArray.test().length).toEqual(1)
})
})//works
Unless you specifically expect the array to be shared among all your tests, you should set it up as follows:
Array.prototype.test = function() {
return this.innerArray()
}
describe('tests', () => {
let sampleArray
beforeEach(() =>
sampleArray = new Array()
})
// tests...
});

Categories

Resources