This feature is available only for projects developed using API version 11 or later based on the stage model.
When previewing a UI, you may not be able to view UI changes resulting from changes of return values. This is because the code runtime environment differs from that of the real device, and valid return values cannot be obtained for certain API calls. For example, when batteryInfo.voltage is called to obtain the battery power level during the preview, a fixed value 0, rather than the actual value, is returned. This is where Hamock comes into the picture. Without changing the service logic, you can mock the attributes or methods of UI components or the imported module APIs.
A dependency on hamock is added to the project- or module-level oh-package.json5 file, and the project sync is complete.
"devDependencies": {
"@ohos/hamock": "1.0.0"
} For any component developed with the declarative paradigm, you can use @MockSetup to decorate a method. When you preview the component, the decorated method is executed during component initialization. Within this method, you can redefine a component method or reassign a value to a component attribute, both taking effect during the preview.
The method decorated by @MockSetup is automatically triggered only in the preview scenario and is executed before the aboutToAppear lifecycle callback of the component.
import { MockKit, when, MockSetup } from '@ohos/hamock'; import { MockKit, when, MockSetup } from '@ohos/hamock';
@Entry
@Component
struct Index {
// ...
@MockSetup
randomName() {
let mocker: MockKit = new MockKit();
let mockfunc: Object = mocker.mockFunc(this, this.method1);
// Mock the return value of the specified method in the specified input parameter.
when(mockfunc)('test').afterReturn(1);
}
// ...
// Invoke the method in the service scenario.
const result = this.method1('test'); // in previewer, result = 1
} import { MockSetup } from '@ohos/hamock'; import { MockSetup } from '@ohos/hamock';
@Component
struct Person {
@Prop species: string;
// Define the target attribute in the @MockSetup fragment.
@MockSetup
randomName() {
this.species = 'primates'
}
// ...
// Invoke the attribute. (This attribute does not change during the period from initialization to invoking.)
const result = this.species // in previewer, result = primates
}
You can mock system modules, dependent modules, and local modules to facilitate testing and previewing. Just create an ArkTS file that contains the mock implementation code, and define the mapping between the real module and its mock in the mock-config.json5 configuration file. The target module and mock implementation code file are in one-to-one mapping. That is, only one mock implementation code file can be used for a target module. During preview, all pages that import the target module will point to the mock implementation code file.
// src/mock/MeasureText.mock.ets
import MeasureText from '@ohos.measure'
// Mock the class via inheritance (using extends).
class MockMeasureText extends MeasureText {
// Define the mock implementation.
static measureText(): number {
console.log('Return value of the mock measureText function')
return 100;
}
};
export default MockMeasureText;
It is recommended that mocking a class be implemented via inheritance (using extends). If inheritance is not used, provide mock implementations for all methods using the dependency module in the code.
{
"@ohos.measure": { // Name of the module to be replaced.
"source": "src/mock/MeasureText.mock.ets" // Path of the mock implementation code, relative to the root directory of the module.
},
} hilog.debug(DomainNumber, logTag, 'Mock %{public}s', `${MeasureText.measureText({textContent: 'Hello World'})}`) // src/mock/module/utils/CommonUtils.mock.ets
// Import the local module.
import LibDefaultExport from '../../../main/ets/utils/CommonUtils'; // get origin default export
import { methodA, ObjectB } from '../../../main/ets/utils/CommonUtils'; // get origin export on demand
class DefaultExportMock extends LibDefaultExport {
// Define the mock implementation.
public static getName(): String {
return "Mocked Name";
}
};
// Mock methodA.
export const methodAMock = (): string => {
return "methodA Mocked"
}
export {
methodAMock as methodA,
ObjectB,
}
export default DefaultExportMock; The following is an example of the CommonUtils.ets file:
export default class CommonUtils {
public static getName(): String {
return "origin name";
}
public static getTitle(): String {
return "origin title";
}
}
export const methodA = (): string => {
return "methodA"
}
export const ObjectB: Object = new Object();
Mocking local modules is only available for the ArkTS and TS file in the src/main/ets directory.
{
"utils/CommonUtils.ets": { // Specify the path of the file relative to the ets directory, including the file name extension.
"source": "src/mock/module/utils/CommonUtils.mock.ets"
},
} hilog.debug(DomainNumber, logTag, 'Mock %{public}s', CommonUtils.getName());