Reputation: 5142
I have the following svelte file
Dashboard.svelte
<script>
import Proxy from "../Proxy.js";
import { onMount } from "svelte";
export let data = [];
onMount(async () => {
spinner = true;
let data = await Proxy.getData();
});
</script>
......
......
......
Dashboard.test.js
import Dashboard from "../src/Dashboard.svelte"
jest.mock("../src/Proxy.js");
describe('Dashboard Component', (next) => {
it('should update data on mount', () => {
const target = document.createElement('div');
const dashboard = new Dashboard({ target });
Proxy.getData.mockResolvedValue([{
"id": "sdadasdas"
}]);
setTimeout(() => {
expect(dashboard.data.length).toBe(1);
next();
}, 10);
})
})
Now, it is not mocking the Proxy.js that I am trying to mock and always going into the inside code.
Any idea what is going wrong here?
Thanks for the help.
Upvotes: 3
Views: 1287
Reputation: 325
Try to mock Proxy.js
before using it internally.
jest.mock("../src/Proxy.js");
import Dashboard from "../src/Dashboard.svelte"
Upvotes: 1
Reputation: 280
I think the proper way to handle this is like below:
import Proxy from "../src/Proxy.js";
import Dashboard from "../src/Dashboard.svelte"
jest.mock("../src/Proxy.js");
describe('Dashboard Component', (next) => {
it('should update data on mount', () => {
Proxy.mockImplementation(() => {
return {
getData: jest.fn().mockResolvedValue([{"id": "sdadasdas"}]);
}
});
const target = document.createElement('div');
const dashboard = new Dashboard({ target });
// I don't know why using setTimeout here, but it's up to you !
setTimeout(() => {
expect(dashboard.data.length).toBe(1);
next();
}, 10);
})
});
Also if you need to mock the getData for another tests you could mock it with passing a second parameter to jest.mock like this:
jest.mock("../src/Proxy.js", () => {
return {
getData: jest.fn().mockResolvedValue([{"id": "sdadasdas"}]);
};
});
I am not aware of the context you are coding but I think another way to mock the getData is like below:
import Proxy from "../src/Proxy.js";
import Dashboard from "../src/Dashboard.svelte"
// Do not use automatic mock
describe('Dashboard Component', (next) => {
it('should update data on mount', () => {
Proxy.getData = jest.fn().mockResolvedValue([{"id": "sdadasdas"}]);
const target = document.createElement('div');
const dashboard = new Dashboard({ target });
// rest of the code ...
})
});
Upvotes: 2