How to mock a module method during detox testing? - javascript

I'm trying mock a module during detox e2e testing :
beforeEach(async () => {
function mockFunctions() {
const original = require.requireActual('react-native-device-info');
return {
...original,
getDeviceCountry: jest.fn(() => {
return 'DE'
})
}
}
await jest.mock('react-native-device-info', () => mockFunctions)
})
It's not working, so I'm wondering if it's even possible?

Related

How would I mock a MutationRecord when testing with JEST

I have a function that does some operations with the MutationRecords collected in a MutationObserver. I would like to test the operations done to these mutations in an unit test. I am using JEST.
I found a way to mock the MutationObserver, but would like to mock the MutationRecords too.
This is my .spec.ts
import { functionWithMutationObserverInside } from "./testingQuestion"
const mutationObserverMock = jest
.fn<MutationObserver, [MutationCallback]>()
.mockImplementation(() => {
return {
observe: jest.fn(),
disconnect: jest.fn(),
takeRecords: jest.fn(),
}
})
global.MutationObserver = mutationObserverMock
const mutations: MutationRecord[] = []
describe("MutationObserver", () => {
it("checks if MutiationObserver is called", () => {
functionWithMutationObserverInside()
const observerCb = mutationObserverMock.mock.calls[0][0]
observerCb(mutations, mutationObserverMock.mock.instances[0])
})
})
Thanks!

Mock import() in jest

I'm struggling to test dynamic imports and I am wondering if there's a way to mock import() so I could simply mock the return value with Promise.resolve(mockComponent)?
The hook I want to test:
useEffect(() => {
async function setup() {
const { default: Player } = await import('#vimeo/player');
playerRef.current = new Player(
playerRef.current,
playerConfig,
);
playerRef.current.on('loaded', () => setIsLoading(false));
}
if (playerRef?.current) {
setup();
}
return () => playerRef.current?.destroy && playerRef.current.destroy();
}, [playerRef]);

jest fn mock isnt working if not assigned in it and assigned in for each

i am trying to write tests using jest
the integration is a call that have a private function called test- gets called by funcTest
trying to mock implementation in before each how ever the mock does not work and it goes to the real function "test".
when i put the assignment (integration['test']=mockFn;) inside the "it" it works perfectly .
example for working code:
describe('test', () => {
const mockFn: jest.Mock = jest.fn();
beforeEach(async () => {
const integration = new integrationTest();
})
afterEach(() => {
jest.restoreAllMocks();
});
it('call mock implemntaion', async () => {
integration['test']=mockFn;
mockFn.mockImplementation(() => {
throw new Error('error');
});
try {
await integration.funcTest();
} catch (e) {
expect(e).toBeInstanceOf(Error);
}
});
})
example of not working code:
describe('test', () => {
const mockFn: jest.Mock = jest.fn();
beforeEach(async () => {
const integration = new integrationTest();
integration['test']=mockFn;
})
afterEach(() => {
jest.restoreAllMocks();
});
it('call mock implemntaion', async () => {
mockFn.mockImplementation(() => {
throw new Error('error');
});
try {
await integration.funcTest();
} catch (e) {
expect(e).toBeInstanceOf(Error);
}
});
})
why does this happen
and how to fix
thanks

Mocking html-pdf using Jest

I am using the html-pdf package in my nodejs code (not in Typescript). Now, this package has a create() function which is chained with the toBuffer() function. I am unit testing my code using Jest and want to mock this call pdf.create(html).toBuffer().
var pdf = require('html-pdf');
pdf.create(html).toBuffer(function(htmlToPdfError, buffer){
if (htmlToPdfError) {
reject(htmlToPdfError);
}
resolve(buffer.toString('base64'));
});
EDIT:
I am trying to use the following code in my spec file to make the module:
jest.mock('html-pdf', () => ({
create: jest.fn(() => {
return Promise.resolve();
})
}));
This is helping me mock the create() function but I do not know how to return a object in Promise.resolve which would have a toBuffer function
I could mock it using the following code:
const mockToBuffer = {
toBuffer: jest.fn((callback: Function) => callback(null, null)),
}
jest.mock('html-pdf', () => ({
create: jest.fn(() => mockToBuffer),
}))
it('Should work', async () => {
const expectedResult = Buffer.from([10])
mockToBuffer.toBuffer.mockImplementation((callback: Function) => {
callback(null, expectedResult)
})
// const result = await yourFuncUsingHtmlPdf(/* fakePayload */)
// Comparing the buffer using the native function
// expect(expectedResult.equals(result)).toBe(true)
}
will this work?
and then assert that your "pdf" buffer contains "test string"?
jest.mock('html-pdf', () => ({
create: jest.fn(() => {
return Promise.resolve({
toBuffer: function(callback) {
callback(null, Buffer.from("test string", "utf-8"));
},
});
})
}));
(I haven't tried it)

Jest Mock - inserting values into tested file

I'm having trouble inserting values into the file under test:
import device from '../device'
let execute = () => {
if (device.isAndroid()) {
return true
else {
return false
}
}
Now for the test file:
jest.mock('../device')
import device from '../device'
describe('when the device is Android', () => {
let device
beforeEach(() => {
device = jest.fn().mockImplementation(() => {
return {
isAndroid: () => { return true }
}
})
})
it('returns true', () => {
let results = execute()
expect(result).toEqual(true)
})
})
The test fails and returns false. What am I doing wrong?
You need to mock '../device' with a jest spy and the mock implementation on that:
jest.mock('../device', ()=>{return {isAndroid: jest.fn()}})
import device from '../device'
describe('when the device is Android', () => {
beforeEach(() => {
device.isAndroid.mockImplementation(() => true)
})
it('returns true', () => {
let results = execute()
expect(result).toEqual(true)
})
})

Categories