Reputation: 3365
I have a class which starts and fires off a setup function in the constructor like so:
import { myFunction } from './util';
export class MyClass {
constructor() {
myFuction()
}
}
And then inside that function I have this:
export function myFunction() {
window.fruit = 'apple';
}
I want to test in Jest that the myFunction()
function gets fired, and that window.fruit
has the property of Apple.
import MyClass from '../index';
import { myFunction } from '../util';
describe('myclass', () => {
const mocks = {
myFunction: jest.fn()
}
const meinclass = new MyClass();
describe('#constructor', () => {
it('should initialize the class', () => {
expect(meinclass).not.toBeUndefined()
})
it('should call myfunction', () => {
const init = jest.spyOn(myFunction);
const fruit = window.fruit
expect(init).toHaveBeenCalled()
expect(fruit).toBe('apple')
})
})
})
I am unsure of the correct way of testing this? I've tried using the .mock
method of Jest also but I seem to be struggling to get it to work. Whenever I even log window
I don't see the property fruit
on it. I feel like there's a larger part of this puzzle I'm missing. Apologies for the simple question.
Upvotes: 0
Views: 2777
Reputation: 110922
I don't think it make sense to test both, that the function was called and that window.fruit
was set correctly. So instead of using window
use global
. Doing it this way you don't need to mock anything.
it('should call myfunction', () => {
const fruit = global.fruit
expect(fruit).toBe('apple')
})
The other way would be only to test that the function was called:
import MyClass from '../index';
import { myFunction } from '../util';
jest.mock('../util', ()=>({myFunction: jest.fn()}))
it('should call myfunction', () => {
expect(myFunction).toHaveBeenCalled()
})
Upvotes: 1