Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add flag to check "is context ready?" #4

Merged
merged 5 commits into from
Jun 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.DS_Store
coverage/
dist/
node_modules/
yarn-error.log*
82 changes: 82 additions & 0 deletions __tests__/index.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import './window.init.mock';

import React from 'react';
import { render, waitFor } from '@testing-library/react';

import { Liff, LiffProvider, useLiff } from '../src/index';

const TestComponent: React.FC = () => {
const { error, liff, ready } = useLiff();

return (
<>
<p data-testid="ready">{ready.toString()}</p>
<p data-testid="error.message">{error?.message ?? ''}</p>
{/* @ts-ignore */}
<p data-testid="liff.id">{liff?.id}</p>
</>
);
};

describe('LiffProvider', () => {
const tree = (stubEnabled: boolean | Partial<Liff>) => (
<LiffProvider liffId={'myLiffId'} stubEnabled={stubEnabled}>
<TestComponent />
</LiffProvider>
);

describe('When stub is disabled', () => {
describe('When the `window.liff.init()` succeeds', () => {
it('shows myLiffId', async () => {
const { getByTestId } = render(tree(false));

await waitFor(() => {
expect(getByTestId('ready').textContent).toBe('true');
expect(getByTestId('error.message').textContent).toBe('');
expect(getByTestId('liff.id').textContent).toBe('myLiffId');
});
});
});

describe('When the `window.liff.init()` failed', () => {
beforeEach(() => {
window.liff.init = jest.fn().mockImplementationOnce(async () => {
throw new Error('Failed to initialize liff.');
});
});

it('shows error message', async () => {
const { getByTestId } = render(tree(false));

await waitFor(() => {
expect(getByTestId('ready').textContent).toBe('false');
expect(getByTestId('error.message').textContent).toBe('Failed to initialize liff.');
});
});
});
});

describe('When stub is enabled (true)', () => {
it('shows stubbed liffId', async () => {
const { getByTestId } = render(tree(true));

await waitFor(() => {
expect(getByTestId('ready').textContent).toBe('true');
expect(getByTestId('error.message').textContent).toBe('');
expect(getByTestId('liff.id').textContent).toBe('liffId');
});
});
});

describe('When stub is enabled (object)', () => {
it('shows overridden liffId', async () => {
const { getByTestId } = render(tree({ id: 'overriddenLiffId' }));

await waitFor(() => {
expect(getByTestId('ready').textContent).toBe('true');
expect(getByTestId('error.message').textContent).toBe('');
expect(getByTestId('liff.id').textContent).toBe('overriddenLiffId');
});
});
});
});
9 changes: 9 additions & 0 deletions __tests__/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"types": ["jest", "liff-type", "react", "testing-library__react"]
},
"include": [
"."
]
}
9 changes: 9 additions & 0 deletions __tests__/window.init.mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Object.defineProperty(window, 'liff', {
writable: true,
value: {
init: jest.fn().mockImplementation(async (options: { liffId: string }) => {
/* @ts-ignore */
window.liff.id = options.liffId;
}),
},
});
11 changes: 11 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module.exports = {
collectCoverageFrom: ['<rootDir>/src/**/*.ts{,x}'],
globals: {
'ts-jest': {
tsConfig: '__tests__/tsconfig.json',
},
},
preset: 'ts-jest',
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/__tests__/**/*.test.ts{,x}'],
};
10 changes: 9 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,29 @@
"clean": "rimraf dist/*",
"eslint": "eslint .",
"eslint:fix": "eslint --fix .",
"prepack": "npm-run-all eslint clean build"
"prepack": "npm-run-all eslint clean build",
"test": "jest",
"test:coverage": "jest --coverage"
},
"devDependencies": {
"@testing-library/react": "^10.2.1",
"@types/jest": "^26.0.0",
"@types/react": "^16.9.36",
"@types/testing-library__react": "^10.0.1",
"@typescript-eslint/eslint-plugin": "^3.2.0",
"@typescript-eslint/parser": "^3.2.0",
"eslint": "^7.2.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.3",
"eslint-plugin-react": "^7.20.0",
"jest": "^26.0.1",
"liff-type": "^2.1.2",
"npm-run-all": "^4.1.5",
"prettier": "^2.0.5",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"rimraf": "^3.0.2",
"ts-jest": "^26.1.0",
"typescript": "^3.9.5"
},
"peerDependencies": {
Expand Down
22 changes: 17 additions & 5 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import React, { createContext, useEffect, useState } from 'react';
export type Liff =
| typeof window.liff
| {
id: string;
getLineVersion: () => string;
permanentLink: {
createUrl: () => string;
Expand All @@ -14,11 +15,14 @@ export type LiffError = {
message: string;
};
export type LiffContext = {
liff: Liff;
error?: LiffError;
liff: Liff;
ready: boolean;
};

const liffStub: Liff = {
id: 'liffId',
ready: new Promise(() => {}),
getOS: () => 'web',
getLanguage: () => 'ja',
getVersion: () => '2.1.3',
Expand All @@ -42,7 +46,12 @@ const liffStub: Liff = {
sub: 'sub',
}),
getContext: () => ({ type: 'none', viewType: 'full' }),
getProfile: async () => ({ userId: 'userId', displayName: 'displayName' }),
getProfile: async () => ({
displayName: 'displayName',
pictureUrl: 'https://example.com/test.jpg',
statusMessage: '',
userId: 'userId',
}),
getFriendship: async () => {
return { friendFlag: true };
},
Expand Down Expand Up @@ -73,7 +82,7 @@ const liffStub: Liff = {
},
};

const context = createContext<LiffContext>({ liff: liffStub });
const context = createContext<LiffContext>({ liff: liffStub, ready: false });
context.displayName = 'LiffContext';

export interface LiffProviderProps {
Expand All @@ -87,26 +96,29 @@ export const LiffProvider: React.FC<LiffProviderProps> = ({
liffId = '',
stubEnabled = false,
}) => {
const [liff, setLiff] = useState<Liff>(liffStub);
const [error, setError] = useState<LiffError>();
const [liff, setLiff] = useState(liffStub);
const [ready, setReady] = useState(false);

useEffect(() => {
if (stubEnabled) {
if (typeof stubEnabled === 'object') {
setLiff({ ...liffStub, ...stubEnabled });
}
setReady(true);
return;
}

window.liff
.init({ liffId })
.then(() => {
setLiff(window.liff);
setReady(true);
})
.catch(e => setError(e));
}, [window.liff]);

return <context.Provider value={{ liff, error }}>{children}</context.Provider>;
return <context.Provider value={{ error, liff, ready }}>{children}</context.Provider>;
};

export const useLiff = (): LiffContext => React.useContext(context);
Loading