# spfx-ut-library

> Helper library for unit testing spfx solutions

Latest version **0.0.4** (published 2021-11-14) · MIT license · 0 weekly downloads

## Install

```sh
npm install spfx-ut-library
pnpm add spfx-ut-library
yarn add spfx-ut-library
bun add spfx-ut-library
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.4 |
| Published | 2021-11-14 |
| First published | 2021-11-09 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 102.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | m.g.wojciechowski@gmail.com |
| Maintainers | mgwojciech |
| Keywords | spfx, unit, test |

## Links

- npm: https://www.npmjs.com/package/spfx-ut-library
- Repository: https://github.com/mgwojciech/spfx-ut-library
- Homepage: https://github.com/mgwojciech/spfx-ut-library#readme
- Issues: https://github.com/mgwojciech/spfx-ut-library/issues
- npm.io page: https://npm.io/package/spfx-ut-library

## Dependencies (1)

- [typescript](https://npm.io/package/typescript.md) ^4.4.4

## Alternatives

- [duck](https://npm.io/package/duck.md) — 4.2M weekly downloads
- [ava](https://npm.io/package/ava.md) — 560.2K weekly downloads
- [storybook-addon-module-mock](https://npm.io/package/storybook-addon-module-mock.md) — 71.7K weekly downloads
- [vest](https://npm.io/package/vest.md) — 50.1K weekly downloads
- [@ethereum-waffle/mock-contract](https://npm.io/package/@ethereum-waffle/mock-contract.md) — 40.0K weekly downloads

## Recent versions

- 0.0.4 (latest) — 2021-11-14
- 0.0.3 — 2021-11-09
- 0.0.2 — 2021-11-09
- 0.0.1 — 2021-11-09

## README

# spfx-ut-library
Mocking library for SPFx

# Setup

This library works best with jest.
Before You begin install jest @types/jest chai @types/chai and ts-jest

    npm i jest @types/jest chai @types/chai ts-jest -D

Then install spfx-ut-library

    npm i spfx-ut-library -D

Now to set jest up add following to Your package.json
```json
{
    ...,
    "jest": {
        "setupFilesAfterEnv": [
        "./tests/setup.ts"
        ],
        "testEnvironment": "jsdom",
        "transform": {
        "^.+\\.(ts|tsx)$": "ts-jest"
        }
    }
}
```
Finally register mocks for spfx static objects and methods.
Add ./tests/setup.ts file to Your project:
```typescript
///<reference types="jest" />

import { JestHelper } from "spfx-ut-library/lib/helpers/JestHelper";
JestHelper.registerMocks(jest);
```
# Using Graph client mock

Let's assume You have a GraphRepositoryFactory which creates GraphRepository. You can use following code to test it.
```typescript
describe("GraphRepository", () => {
    test("GraphRepositoryFactory", async () => {
        let mockContext = new SPWebPartContextMock();
        mockContext.msGraphClientFactory.mockClient.onRequestExecutingCallback = (request) => {
            if (request.path.indexOf("/sites/contoso.sharepoint.com:/sites/test-site:/lists/test-list-id") >= 0) {
                return {
                    value: [
                        {
                            ID: 1,
                            Title: "Test item 1"
                        }
                    ]
                }
            }
        }
        let factory = new GraphRepositoryFactory(mockContext as any);
        let repo = await factory.getRepository("test-list-id");

        assert.isOk(sth);

        let listItems = await sth.getListItems();

        assert.deepEqual(listItems, [
            {
                ID: 1,
                Title: "Test item 1"
            }
        ])
    });
});
```
# Using SPHttpClient mock
Let's assume You have a SPItemRepository which sends requests to SharePoint using context.spHttpClient. You can mock it using following code.
```typescript
describe("SPItemRepository", ()=>{
    test("SPItemRepository", async () => {
        let mockContext = new SPWebPartContextMock();
        let provider: MockHttpClient = mockContext.serviceScope.consume(MockHttpClient.spHttpClientServiceKey);
        provider.registerResponse({
            url: "https://contoso.sharepoint.com/sites/test-site/_api/web/lists/test-list-id/items?$expand=fields&$top=5",
            method: "GET",
            ok: true,
            response: JSON.stringify({
                value: [
                    {
                        ID: 1,
                        Title: "Test item 1"
                    }
                ]
            })
        });

        let repo = new SPItemsRepository(provider as any, mockContext.pageContext.site.absoluteUrl, "test-list-id");

        let listItems = await repo.getListItems();

        assert.deepEqual(listItems, [
            {
                ID: 1,
                Title: "Test item 1"
            }
        ])
    });
});
```
# Using AadTokenProviderMock
Let's assume you have GraphTokenProvider that uses AadTokenProvider to obtain Graph token. You can mock it using following code.
```typescript
describe("GraphTokenProvider", () => {
	let mockContext = new SPWebPartContextMock();

    afterEach(() => {
        mockContext.aadTokenProviderFactory.aadTokenProviderMock.clearMocks();
    });

	test("Should return graph token", async () => {
        const TOKEN = "token";
		mockContext.aadTokenProviderFactory.aadTokenProviderMock.registerToken("https://graph.microsoft.com", TOKEN);
		const tokenProvider = new GraphTokenProvider(mockContext as any);
        const token = await tokenProvider.getToken();
        assert.equal(token, TOKEN);
	});
});
```

---
_Source: https://npm.io/package/spfx-ut-library · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
