// utils.ts
export const handleClick = (): void => {
console.log('Handle click by user code');
}
In order to correctly mock handleClick method from utils.ts source code of test file and dependencies which used mocked module modified in runtime. Test file will looks like:
import of original module utils moved to the top and saves to generated variable - __testplane_import_1__. It is used in order to correctly mock module (for example if user mock only on method);
import of fn and mock also moved to the top in order to call mock before import all other modules;
call mock with await and send original module as third argument. Moreover move it to the top. Here used mock from src/runner/browser-env/vite/browser-modules/mock.ts which is async.
import all other modules using dynamic imports. It is necessary in order to correctly mock module and then import all other deps in which mocked module can be imported. Without dynamic import modules will imported first and then await mock will be executed;
for mocked module use helper importWithMock which gets mocked implementation of module instead of original module.
Component file will looks like (after modify in runtime):
import * as __testplane_import_2__ from './tests/utils';
const {handleClick} = importWithMock("./tests/utils", __testplane_import_2__);
export default function App() {
// ...
}
What happens:
like in test file we save original module to special variable - __testplane_import_2__;
import mocked module using helper importWithMock
Discuss:
Should rename new exported file mock for something more understandable? This file not only export mock and unmock methods but also spied: fn, spyOn. Moreover this module works only in browser environment. And can't be called in node env.
What is done:
Implement ability to mock modules and use spies in component testing. The same as in jest.
How it works
I'll explain it with a simple example:
In order to correctly mock
handleClick
method fromutils.ts
source code of test file and dependencies which used mocked module modified in runtime. Test file will looks like:What happens:
utils
moved to the top and saves to generated variable -__testplane_import_1__
. It is used in order to correctly mock module (for example if user mock only on method);fn
andmock
also moved to the top in order to callmock
before import all other modules;mock
withawait
and send original module as third argument. Moreover move it to the top. Here usedmock
fromsrc/runner/browser-env/vite/browser-modules/mock.ts
which is async.await mock
will be executed;importWithMock
which gets mocked implementation of module instead of original module.Component file will looks like (after modify in runtime):
What happens:
__testplane_import_2__
;importWithMock
Discuss:
mock
for something more understandable? This file not only exportmock
andunmock
methods but also spied:fn
,spyOn
. Moreover this module works only in browser environment. And can't be called in node env.