我该如何为Sharepoint Web部件编写测试



如何在Sharepoint Web部件中进行单元测试CRUD方法?关于创建类/特定方法的Mock,我已经尝试过遵循Jest文档,但我认为这是不可能的,因为我应该测试的服务类需要构造函数的特定上下文。

export default class PnpServices implements IPnpServices {
private _sp;
constructor(context: WebPartContext) {
this._sp = getSP(context);
}
public async sp_createItem(listName: string, itemObject: any): Promise<any> {
try {
const iar: IItemAddResult = await this
._sp.web.lists.getByTitle(listName).items.add(itemObject)
return iar.data.Id;
} catch (e) {
throw new Error("error")
}
}

我尝试设置一个简单的测试来检查构造函数是否可以在解析";空";作为自变量而不是上下文

jest.mock('./pnpservices')
it('should pass', () => {
const mockedClassInstance = new PnpServices(null);
expect(PnpServices).toBeCalledTimes(1);
})

我能找到的大多数例子都没有创建真正有用的测试,甚至没有像CRUD这样面向业务的方法,它们大多只是简单的"测试";加法";方法或其唯一的功能是返回console.log。

有什么帮助吗?

使用SPFx web部件并不容易。首先,jest本身并不是开箱即用的,tou有很多东西需要安装和配置。我关注了这篇文章,几年前它或多或少奏效了:

https://www.eliostruyf.com/sharepoint-framework-unit-tests-with-jest/

由于你似乎也在同一个项目中使用pnpjs,你可能想看看这个:

https://github.com/pnp/pnpjs/issues/1425

最新更新