要进行Aurelia单元测试以访问组件的viewModel,可以使用以下解决方法:
安装所需的依赖项:
npm install aurelia-testing --save-dev
创建一个测试文件,例如component.spec.js
。
在测试文件中导入必要的依赖项:
import { StageComponent } from 'aurelia-testing';
import { bootstrap } from 'aurelia-bootstrapper';
import { MyComponent } from 'path/to/my-component';
定义测试套件并设置测试环境:
describe('MyComponent', () => {
let component;
beforeEach(() => {
component = StageComponent.withResources('path/to/my-component')
.inView(' ');
});
afterEach(() => {
component.dispose();
});
it('should access viewModel', done => {
component.create(bootstrap).then(() => {
const viewModel = component.viewModel;
// 对 viewModel 进行断言或操作
expect(viewModel.someProperty).toBe('someValue');
done();
}).catch(e => console.error(e.toString()));
});
});
运行测试:
npx jasmine
在上述代码中,我们使用了StageComponent
来创建一个组件实例,并使用.withResources()
指定要测试的组件。然后,我们在测试套件的beforeEach
和afterEach
函数中创建和销毁组件实例。在测试用例中,我们通过component.create(bootstrap)
来创建组件,并使用component.viewModel
访问组件的viewModel。然后,我们可以对viewModel进行断言或操作。
请注意,上述示例是基于Jasmine测试框架的。如果你在使用其他测试框架,可以根据需要进行适当的调整。