Compare commits

..

4 Commits

Author SHA1 Message Date
Adolfo R. Brandes
021f52b303 feat: remove upgrade button
This removes the upgrade button as default content in CourseCardActionSlot.

This is, for the moment, a Sumac-specific change.  The button is still
present in master, pending proper removal (including the component
definitions from the rest of the repository) prior to the U release by
the maintainers.  See:

https://github.com/openedx/frontend-app-learner-dashboard/issues/438
2024-12-06 15:55:31 -03:00
Adolfo R. Brandes
8e0e217402 fix: Use browserslist-config
We were installing browserslist-config but not declaring it.  This had
the effect that webpack - and likely others - were not using it.
2024-12-06 11:08:23 -03:00
Diana Olarte
261448dee9 fix: display programs tab only if it is configured
fix: apply feedback
2024-12-02 07:50:28 -08:00
Diana Olarte
5ef5ed954c fix: display SUPPORT_URL only if the url is configured 2024-12-02 07:50:28 -08:00
241 changed files with 15741 additions and 10573 deletions

4
.env
View File

@@ -32,6 +32,7 @@ ENTERPRISE_MARKETING_UTM_SOURCE=''
ENTERPRISE_MARKETING_UTM_CAMPAIGN='' ENTERPRISE_MARKETING_UTM_CAMPAIGN=''
ENTERPRISE_MARKETING_FOOTER_UTM_MEDIUM='' ENTERPRISE_MARKETING_FOOTER_UTM_MEDIUM=''
LEARNING_BASE_URL='' LEARNING_BASE_URL=''
ZENDESK_KEY=''
HOTJAR_APP_ID='' HOTJAR_APP_ID=''
HOTJAR_VERSION='6' HOTJAR_VERSION='6'
HOTJAR_DEBUG='' HOTJAR_DEBUG=''
@@ -41,6 +42,3 @@ ENABLE_NOTICES=''
CAREER_LINK_URL='' CAREER_LINK_URL=''
ENABLE_EDX_PERSONAL_DASHBOARD=false ENABLE_EDX_PERSONAL_DASHBOARD=false
ENABLE_PROGRAMS=false ENABLE_PROGRAMS=false
NON_BROWSABLE_COURSES=false
# Fallback in local style files
PARAGON_THEME_URLS={}

View File

@@ -38,6 +38,7 @@ ENTERPRISE_MARKETING_UTM_CAMPAIGN='example.com Referral'
ENTERPRISE_MARKETING_FOOTER_UTM_MEDIUM='Footer' ENTERPRISE_MARKETING_FOOTER_UTM_MEDIUM='Footer'
LEARNING_BASE_URL='http://localhost:2000' LEARNING_BASE_URL='http://localhost:2000'
SESSION_COOKIE_DOMAIN='localhost' SESSION_COOKIE_DOMAIN='localhost'
ZENDESK_KEY=''
HOTJAR_APP_ID='' HOTJAR_APP_ID=''
HOTJAR_VERSION='6' HOTJAR_VERSION='6'
HOTJAR_DEBUG='' HOTJAR_DEBUG=''
@@ -47,6 +48,3 @@ ENABLE_NOTICES=''
CAREER_LINK_URL='' CAREER_LINK_URL=''
ENABLE_EDX_PERSONAL_DASHBOARD=false ENABLE_EDX_PERSONAL_DASHBOARD=false
ENABLE_PROGRAMS=false ENABLE_PROGRAMS=false
NON_BROWSABLE_COURSES=false
# Fallback in local style files
PARAGON_THEME_URLS={}

View File

@@ -37,6 +37,7 @@ ENTERPRISE_MARKETING_UTM_SOURCE='example.com'
ENTERPRISE_MARKETING_UTM_CAMPAIGN='example.com Referral' ENTERPRISE_MARKETING_UTM_CAMPAIGN='example.com Referral'
ENTERPRISE_MARKETING_FOOTER_UTM_MEDIUM='Footer' ENTERPRISE_MARKETING_FOOTER_UTM_MEDIUM='Footer'
LEARNING_BASE_URL='http://localhost:2000' LEARNING_BASE_URL='http://localhost:2000'
ZENDESK_KEY='test-zendesk-key'
HOTJAR_APP_ID='hot-jar-app-id' HOTJAR_APP_ID='hot-jar-app-id'
HOTJAR_VERSION='6' HOTJAR_VERSION='6'
HOTJAR_DEBUG='' HOTJAR_DEBUG=''
@@ -46,5 +47,3 @@ ENABLE_NOTICES=''
CAREER_LINK_URL='' CAREER_LINK_URL=''
ENABLE_EDX_PERSONAL_DASHBOARD=true ENABLE_EDX_PERSONAL_DASHBOARD=true
ENABLE_PROGRAMS=false ENABLE_PROGRAMS=false
NON_BROWSABLE_COURSES=false
PARAGON_THEME_URLS={}

1
.github/CODEOWNERS vendored Normal file
View File

@@ -0,0 +1 @@
* @openedx/2U-aperture

View File

@@ -11,15 +11,18 @@ on:
jobs: jobs:
tests: tests:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy:
matrix:
node: [18, 20]
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@v4
- name: Setup Nodejs - name: Setup Nodejs
uses: actions/setup-node@v6 uses: actions/setup-node@v4
with: with:
node-version-file: '.nvmrc' node-version: ${{ matrix.node }}
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
@@ -29,9 +32,6 @@ jobs:
- name: Lint - name: Lint
run: npm run lint run: npm run lint
- name: Type check
run: npm run types
- name: Test - name: Test
run: npm run test run: npm run test
@@ -40,7 +40,24 @@ jobs:
run: npm run build run: npm run build
- name: Run Coverage - name: Run Coverage
uses: codecov/codecov-action@v5 uses: codecov/codecov-action@v4
with: with:
token: ${{ secrets.CODECOV_TOKEN }} token: ${{ secrets.CODECOV_TOKEN }}
fail_ci_if_error: true fail_ci_if_error: true
- name: Send failure notification
if: ${{ failure() }}
uses: dawidd6/action-send-mail@v3
with:
server_address: email-smtp.us-east-1.amazonaws.com
server_port: 465
username: ${{ secrets.EDX_SMTP_USERNAME }}
password: ${{ secrets.EDX_SMTP_PASSWORD }}
subject: CI workflow failed in ${{github.repository}}
to: masters-grades@edx.org,aperture@2u-internal.opsgenie.net
from: github-actions <github-actions@edx.org>
nodemailerlog: true
nodemailerdebug: true
body: CI workflow in ${{github.repository}} failed!
For details see "github.com/${{ github.repository }}/actions/runs/${{ github.run_id
}}"

35
.github/workflows/npm-publish.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
name: Release CI
on:
push:
tags:
- "*"
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Nodejs Env
run: echo "NODE_VER=`cat .nvmrc`" >> $GITHUB_ENV
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VER }}
- name: Install dependencies
run: npm ci
- name: Create Build
run: npm run build
- name: Release Package
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
run: npm semantic-release

4
.husky/pre-push Executable file
View File

@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run lint

2
.nvmrc
View File

@@ -1 +1 @@
24 20

27
.releaserc Normal file
View File

@@ -0,0 +1,27 @@
{
"branch": "master",
"tagFormat": "v${version}",
"verifyConditions": [
"@semantic-release/npm",
{
"path": "@semantic-release/github",
"assets": {
"path": "dist/*"
}
}
],
"analyzeCommits": "@semantic-release/commit-analyzer",
"generateNotes": "@semantic-release/release-notes-generator",
"prepare": "@semantic-release/npm",
"publish": [
"@semantic-release/npm",
{
"path": "@semantic-release/github",
"assets": {
"path": "dist/*"
}
}
],
"success": [],
"fail": []
}

View File

@@ -47,11 +47,10 @@ pull_translations:
&& atlas pull $(ATLAS_OPTIONS) \ && atlas pull $(ATLAS_OPTIONS) \
translations/frontend-platform/src/i18n/messages:frontend-platform \ translations/frontend-platform/src/i18n/messages:frontend-platform \
translations/paragon/src/i18n/messages:paragon \ translations/paragon/src/i18n/messages:paragon \
translations/frontend-component-header/src/i18n/messages:frontend-component-header \
translations/frontend-component-footer/src/i18n/messages:frontend-component-footer \ translations/frontend-component-footer/src/i18n/messages:frontend-component-footer \
translations/frontend-app-learner-dashboard/src/i18n/messages:frontend-app-learner-dashboard translations/frontend-app-learner-dashboard/src/i18n/messages:frontend-app-learner-dashboard
$(intl_imports) frontend-platform paragon frontend-component-header frontend-component-footer frontend-app-learner-dashboard $(intl_imports) frontend-platform paragon frontend-component-footer frontend-app-learner-dashboard
# This target is used by CI. # This target is used by CI.
validate-no-uncommitted-package-lock-changes: validate-no-uncommitted-package-lock-changes:

View File

@@ -39,12 +39,22 @@ The parts of this MFE that can be customized in that manner are documented `here
Contributing Contributing
------------ ------------
Contributions are very welcome. Please read `So you want to contribute to Open edX <https://docs.openedx.org/en/latest/developers/quickstarts/so_you_want_to_contribute.html>`_ for details on how to get started as an Open edX contributor. A core goal of this app is to provide a clean experimentation interface. To promote this end, we have provided a
silo'ed code directory at ``src/widgets`` in which contributors should add their custom widget components. In order to
ensure our ability to maintain the code stability of the app, the code for these widgets should be strictly contained
within the bounds of that directory.
This project is currently accepting all types of contributions — bug fixes, security fixes, maintenance work, or new features. Once written, the widgets can be configured into one of our widget containers at ``src/containers/WidgetContainers``.
However, if you intend to add a new feature, make sure it has gone through the `Product Review process <https://openedx.atlassian.net/wiki/spaces/COMM/pages/3875962884/How+to+submit+an+open+source+contribution+for+Product+Review>`_. This can include conditional logic, as well as Optimizely triggers. It is important to note that our integration tests
will isolate and ignore these containers, and thus testing your widget is the response of the creator/maintainer of the
widget itself.
When proposing a change, create an issue in this repo to get the discussion started. Some guidelines for writing widgets:
* Code for the widget should be strictly confined to the ``src/widgets`` directory.
* You can load data from the redux store, but should not add or modify fields in that structure.
* Network events should be managed in component hooks, though can use our ``data/constants/requests:requestStates`` for
ease of tracking the request states.
License License
------- -------

View File

@@ -17,7 +17,6 @@ metadata:
openedx.org/arch-interest-groups: "" openedx.org/arch-interest-groups: ""
# This can be multiple comma-separated projects. # This can be multiple comma-separated projects.
openedx.org/add-to-projects: "openedx:23" openedx.org/add-to-projects: "openedx:23"
openedx.org/release: "master"
spec: spec:
type: 'service' type: 'service'
lifecycle: 'production' lifecycle: 'production'

View File

@@ -24,7 +24,6 @@ module.exports = {
BASE_URL: 'localhost:1996', BASE_URL: 'localhost:1996',
LMS_BASE_URL: 'http://localhost:18000', LMS_BASE_URL: 'http://localhost:18000',
ECOMMERCE_BASE_URL: 'http://localhost:18130', ECOMMERCE_BASE_URL: 'http://localhost:18130',
CREDIT_PURCHASE_URL: 'http://localhost:8140',
LOGIN_URL: 'http://localhost:18000/login', LOGIN_URL: 'http://localhost:18000/login',
LOGOUT_URL: 'http://localhost:18000/logout', LOGOUT_URL: 'http://localhost:18000/logout',
LOGO_URL: 'https://edx-cdn.org/v3/default/logo.svg', LOGO_URL: 'https://edx-cdn.org/v3/default/logo.svg',
@@ -60,6 +59,7 @@ module.exports = {
ENTERPRISE_MARKETING_FOOTER_UTM_MEDIUM: 'Footer', ENTERPRISE_MARKETING_FOOTER_UTM_MEDIUM: 'Footer',
LEARNING_BASE_URL: 'http://localhost:2000', LEARNING_BASE_URL: 'http://localhost:2000',
SESSION_COOKIE_DOMAIN: 'localhost', SESSION_COOKIE_DOMAIN: 'localhost',
ZENDESK_KEY: '',
HOTJAR_APP_ID: '', HOTJAR_APP_ID: '',
HOTJAR_VERSION: 6, HOTJAR_VERSION: 6,
HOTJAR_DEBUG: '', HOTJAR_DEBUG: '',

9
openedx.yaml Normal file
View File

@@ -0,0 +1,9 @@
# This file describes this Open edX repo, as described in OEP-2:
# http://open-edx-proposals.readthedocs.io/en/latest/oeps/oep-0002.html#specification
tags:
- frontend-app
- masters
oeps:
oep-2: true # Repository metadata
openedx-release: {ref: master}

17117
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -16,11 +16,11 @@
"lint-fix": "fedx-scripts eslint --fix --ext .jsx,.js src/", "lint-fix": "fedx-scripts eslint --fix --ext .jsx,.js src/",
"semantic-release": "semantic-release", "semantic-release": "semantic-release",
"start": "fedx-scripts webpack-dev-server --progress", "start": "fedx-scripts webpack-dev-server --progress",
"dev": "PUBLIC_PATH=/learner-dashboard/ MFE_CONFIG_API_URL='http://localhost:8000/api/mfe_config/v1' fedx-scripts webpack-dev-server --progress --host apps.local.openedx.io",
"test": "TZ=GMT fedx-scripts jest --coverage --passWithNoTests", "test": "TZ=GMT fedx-scripts jest --coverage --passWithNoTests",
"quality": "npm run lint-fix && npm run test", "quality": "npm run lint-fix && npm run test",
"watch-tests": "jest --watch", "watch-tests": "jest --watch",
"types": "tsc --noEmit" "snapshot": "fedx-scripts jest --updateSnapshot",
"prepare": "husky install"
}, },
"author": "edX", "author": "edX",
"license": "AGPL-3.0", "license": "AGPL-3.0",
@@ -30,57 +30,70 @@
}, },
"dependencies": { "dependencies": {
"@edx/brand": "npm:@openedx/brand-openedx@^1.2.2", "@edx/brand": "npm:@openedx/brand-openedx@^1.2.2",
"@edx/frontend-component-footer": "^14.6.0", "@edx/frontend-component-header": "^5.6.0",
"@edx/frontend-component-header": "^6.6.0", "@edx/frontend-enterprise-hotjar": "3.0.0",
"@edx/frontend-enterprise-hotjar": "7.2.0", "@edx/frontend-platform": "8.1.2",
"@edx/frontend-platform": "^8.3.1", "@edx/openedx-atlas": "^0.6.0",
"@edx/openedx-atlas": "^0.7.0", "@edx/react-unit-test-utils": "3.0.0",
"@fortawesome/fontawesome-svg-core": "^1.2.36", "@fortawesome/fontawesome-svg-core": "^1.2.36",
"@fortawesome/free-brands-svg-icons": "^5.15.4", "@fortawesome/free-brands-svg-icons": "^5.15.4",
"@fortawesome/free-solid-svg-icons": "^5.15.4", "@fortawesome/free-solid-svg-icons": "^5.15.4",
"@fortawesome/react-fontawesome": "^0.2.0", "@fortawesome/react-fontawesome": "^0.2.0",
"@openedx/frontend-plugin-framework": "^1.7.0", "@openedx/frontend-plugin-framework": "^1.2.0",
"@openedx/paragon": "^23.4.5", "@openedx/frontend-slot-footer": "^1.0.2",
"@openedx/paragon": "^22.2.2",
"@redux-beacon/segment": "^1.1.0",
"@redux-devtools/extension": "3.3.0", "@redux-devtools/extension": "3.3.0",
"@reduxjs/toolkit": "^2.0.0", "@reduxjs/toolkit": "^1.6.1",
"@testing-library/user-event": "^13.5.0",
"classnames": "^2.3.1", "classnames": "^2.3.1",
"core-js": "3.46.0", "core-js": "3.38.1",
"filesize": "^10.0.0", "dompurify": "^2.3.1",
"email-prop-type": "^3.0.1",
"file-saver": "^2.0.5",
"filesize": "^8.0.6",
"font-awesome": "4.7.0", "font-awesome": "4.7.0",
"history": "5.3.0", "history": "5.3.0",
"html-react-parser": "^1.3.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "29.7.0",
"jest-when": "^3.6.0",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"moment": "^2.29.4", "moment": "^2.29.4",
"prop-types": "15.8.1", "prop-types": "15.8.1",
"react": "^18.3.1", "query-string": "7.1.3",
"react-dom": "^18.3.1", "react": "^17.0.2",
"react-dom": "^17.0.2",
"react-helmet": "^6.1.0", "react-helmet": "^6.1.0",
"react-intl": "6.8.9", "react-intl": "6.8.0",
"react-pdf": "^7.0.0",
"react-redux": "^7.2.4", "react-redux": "^7.2.4",
"react-router-dom": "6.30.1", "react-router-dom": "6.27.0",
"react-share": "^4.4.0", "react-share": "^4.4.0",
"react-zendesk": "^0.1.13",
"redux": "4.2.1", "redux": "4.2.1",
"redux-beacon": "^2.1.0",
"redux-logger": "3.0.6", "redux-logger": "3.0.6",
"redux-thunk": "2.4.2", "redux-thunk": "2.4.2",
"regenerator-runtime": "^0.14.0", "regenerator-runtime": "^0.14.0",
"reselect": "^4.0.0", "reselect": "^4.0.0",
"universal-cookie": "^4.0.4", "universal-cookie": "^4.0.4",
"util": "^0.12.4" "util": "^0.12.4",
"whatwg-fetch": "^3.6.2"
}, },
"devDependencies": { "devDependencies": {
"@edx/browserslist-config": "^1.3.0", "@edx/browserslist-config": "^1.3.0",
"@edx/typescript-config": "^1.1.0", "@edx/reactifex": "^2.1.1",
"@openedx/frontend-build": "^14.6.2", "@openedx/frontend-build": "14.1.5",
"@testing-library/jest-dom": "^6.6.3", "@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^16.2.0", "@testing-library/react": "^12.1.0",
"@testing-library/user-event": "^14.6.1", "copy-webpack-plugin": "^12.0.0",
"copy-webpack-plugin": "^13.0.0", "husky": "^9.0.0",
"identity-obj-proxy": "^3.0.0", "identity-obj-proxy": "^3.0.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"jest-expect-message": "^1.1.3", "jest-expect-message": "^1.1.3",
"jest-when": "^3.6.0",
"react-dev-utils": "^12.0.0", "react-dev-utils": "^12.0.0",
"react-test-renderer": "^18.3.1", "react-test-renderer": "^17.0.2",
"redux-mock-store": "^1.5.4" "redux-mock-store": "^1.5.4",
"semantic-release": "^20.1.3"
} }
} }

View File

@@ -6,7 +6,7 @@ import { logError } from '@edx/frontend-platform/logging';
import { initializeHotjar } from '@edx/frontend-enterprise-hotjar'; import { initializeHotjar } from '@edx/frontend-enterprise-hotjar';
import { ErrorPage, AppContext } from '@edx/frontend-platform/react'; import { ErrorPage, AppContext } from '@edx/frontend-platform/react';
import { FooterSlot } from '@edx/frontend-component-footer'; import FooterSlot from '@openedx/frontend-slot-footer';
import { Alert } from '@openedx/paragon'; import { Alert } from '@openedx/paragon';
import { RequestKeys } from 'data/constants/requests'; import { RequestKeys } from 'data/constants/requests';
@@ -22,7 +22,7 @@ import track from 'tracking';
import fakeData from 'data/services/lms/fakeData/courses'; import fakeData from 'data/services/lms/fakeData/courses';
import AppWrapper from 'containers/AppWrapper'; import AppWrapper from 'containers/WidgetContainers/AppWrapper';
import LearnerDashboardHeader from 'containers/LearnerDashboardHeader'; import LearnerDashboardHeader from 'containers/LearnerDashboardHeader';
import { getConfig } from '@edx/frontend-platform'; import { getConfig } from '@edx/frontend-platform';
@@ -80,7 +80,7 @@ export const App = () => {
<div> <div>
<AppWrapper> <AppWrapper>
<LearnerDashboardHeader /> <LearnerDashboardHeader />
<main id="main"> <main>
{hasNetworkFailure {hasNetworkFailure
? ( ? (
<Alert variant="danger"> <Alert variant="danger">

View File

@@ -1,10 +1,13 @@
// frontend-app-*/src/index.scss // frontend-app-*/src/index.scss
@use "@openedx/paragon/styles/css/core/custom-media-breakpoints" as paragonCustomMediaBreakpoints; @import "~@edx/brand/paragon/fonts";
@import "~@edx/brand/paragon/variables";
@import "~@openedx/paragon/scss/core/core";
@import "~@edx/brand/paragon/overrides";
$fa-font-path: "~font-awesome/fonts"; $fa-font-path: "~font-awesome/fonts";
@import "~font-awesome/scss/font-awesome"; @import "~font-awesome/scss/font-awesome";
$input-focus-box-shadow: var(--pgn-elevation-form-input-base); // hack to get upgrade to paragon 4.0.0 to work $input-focus-box-shadow: $input-box-shadow; // hack to get upgrade to paragon 4.0.0 to work
@import "~@edx/frontend-component-header/dist/index"; @import "~@edx/frontend-component-header/dist/index";
@import "~@edx/frontend-component-footer/dist/_footer"; @import "~@edx/frontend-component-footer/dist/_footer";

View File

@@ -1,19 +1,24 @@
import { render, screen, waitFor } from '@testing-library/react'; import React from 'react';
import { Helmet } from 'react-helmet';
import { shallow } from '@edx/react-unit-test-utils';
import { IntlProvider } from '@edx/frontend-platform/i18n'; import { useIntl } from '@edx/frontend-platform/i18n';
import { getConfig } from '@edx/frontend-platform'; import { getConfig } from '@edx/frontend-platform';
import { RequestKeys } from 'data/constants/requests'; import { RequestKeys } from 'data/constants/requests';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import Dashboard from 'containers/Dashboard';
import LearnerDashboardHeader from 'containers/LearnerDashboardHeader';
import AppWrapper from 'containers/WidgetContainers/AppWrapper';
import { App } from './App'; import { App } from './App';
import messages from './messages'; import messages from './messages';
jest.mock('@edx/frontend-component-footer', () => ({ jest.mock('@edx/frontend-component-footer', () => ({ FooterSlot: 'Footer' }));
FooterSlot: jest.fn(() => <div>FooterSlot</div>),
})); jest.mock('containers/Dashboard', () => 'Dashboard');
jest.mock('containers/Dashboard', () => jest.fn(() => <div>Dashboard</div>)); jest.mock('containers/LearnerDashboardHeader', () => 'LearnerDashboardHeader');
jest.mock('containers/LearnerDashboardHeader', () => jest.fn(() => <div>LearnerDashboardHeader</div>)); jest.mock('components/ZendeskFab', () => 'ZendeskFab');
jest.mock('containers/AppWrapper', () => jest.fn(({ children }) => <div className="AppWrapper">{children}</div>)); jest.mock('containers/WidgetContainers/AppWrapper', () => 'AppWrapper');
jest.mock('data/redux', () => ({ jest.mock('data/redux', () => ({
selectors: 'redux.selectors', selectors: 'redux.selectors',
actions: 'redux.actions', actions: 'redux.actions',
@@ -32,103 +37,119 @@ jest.mock('@edx/frontend-platform', () => ({
getConfig: jest.fn(() => ({})), getConfig: jest.fn(() => ({})),
})); }));
jest.mock('@edx/frontend-platform/react', () => ({
...jest.requireActual('@edx/frontend-platform/react'),
ErrorPage: () => 'ErrorPage',
}));
const loadData = jest.fn(); const loadData = jest.fn();
reduxHooks.useLoadData.mockReturnValue(loadData); reduxHooks.useLoadData.mockReturnValue(loadData);
const supportEmail = 'test@support.com'; let el;
const supportEmail = 'test-support-url';
reduxHooks.usePlatformSettingsData.mockReturnValue({ supportEmail }); reduxHooks.usePlatformSettingsData.mockReturnValue({ supportEmail });
describe('App router component', () => { describe('App router component', () => {
const { formatMessage } = useIntl();
describe('component', () => { describe('component', () => {
const runBasicTests = () => { const runBasicTests = () => {
it('displays title in helmet component', async () => { test('snapshot', () => { expect(el.snapshot).toMatchSnapshot(); });
await waitFor(() => expect(document.title).toEqual(messages.pageTitle.defaultMessage)); it('displays title in helmet component', () => {
const control = el.instance
.findByType(Helmet)[0]
.findByType('title')[0];
expect(control.children[0].el).toEqual(formatMessage(messages.pageTitle));
}); });
it('displays learner dashboard header', () => { it('displays learner dashboard header', () => {
const learnerDashboardHeader = screen.getByText('LearnerDashboardHeader'); expect(el.instance.findByType(LearnerDashboardHeader).length).toEqual(1);
expect(learnerDashboardHeader).toBeInTheDocument();
}); });
it('wraps the header and main components in an AppWrapper widget container', () => { it('wraps the header and main components in an AppWrapper widget container', () => {
const appWrapper = screen.getByText('LearnerDashboardHeader').parentElement; const container = el.instance.findByType(AppWrapper)[0];
expect(appWrapper).toHaveClass('AppWrapper'); expect(container.children[0].type).toEqual('LearnerDashboardHeader');
expect(appWrapper.children[1].id).toEqual('main'); expect(container.children[1].type).toEqual('main');
});
it('displays footer slot', () => {
const footerSlot = screen.getByText('FooterSlot');
expect(footerSlot).toBeInTheDocument();
}); });
}; };
describe('no network failure', () => { describe('no network failure', () => {
beforeEach(() => { beforeAll(() => {
jest.clearAllMocks();
reduxHooks.useRequestIsFailed.mockReturnValue(false); reduxHooks.useRequestIsFailed.mockReturnValue(false);
getConfig.mockReturnValue({}); getConfig.mockReturnValue({});
render(<IntlProvider locale="en"><App /></IntlProvider>); el = shallow(<App />);
}); });
runBasicTests(); runBasicTests();
it('loads dashboard', () => { it('loads dashboard', () => {
const dashboard = screen.getByText('Dashboard'); const main = el.instance.findByType('main')[0];
expect(dashboard).toBeInTheDocument(); expect(main.children.length).toEqual(1);
const dashboard = main.children[0];
expect(dashboard.type).toEqual('Dashboard');
expect(
dashboard.matches(shallow(<Dashboard />)),
).toEqual(true);
}); });
}); });
describe('no network failure with optimizely url', () => { describe('no network failure with optimizely url', () => {
beforeEach(() => { beforeAll(() => {
jest.clearAllMocks();
reduxHooks.useRequestIsFailed.mockReturnValue(false); reduxHooks.useRequestIsFailed.mockReturnValue(false);
getConfig.mockReturnValue({ OPTIMIZELY_URL: 'fake.url' }); getConfig.mockReturnValue({ OPTIMIZELY_URL: 'fake.url' });
render(<IntlProvider locale="en"><App /></IntlProvider>); el = shallow(<App />);
}); });
runBasicTests(); runBasicTests();
it('loads dashboard', () => { it('loads dashboard', () => {
const dashboard = screen.getByText('Dashboard'); const main = el.instance.findByType('main')[0];
expect(dashboard).toBeInTheDocument(); expect(main.children.length).toEqual(1);
const dashboard = main.children[0];
expect(dashboard.type).toEqual('Dashboard');
expect(
dashboard.matches(shallow(<Dashboard />)),
).toEqual(true);
}); });
}); });
describe('no network failure with optimizely project id', () => { describe('no network failure with optimizely project id', () => {
beforeEach(() => { beforeAll(() => {
jest.clearAllMocks();
reduxHooks.useRequestIsFailed.mockReturnValue(false); reduxHooks.useRequestIsFailed.mockReturnValue(false);
getConfig.mockReturnValue({ OPTIMIZELY_PROJECT_ID: 'fakeId' }); getConfig.mockReturnValue({ OPTIMIZELY_PROJECT_ID: 'fakeId' });
render(<IntlProvider locale="en"><App /></IntlProvider>); el = shallow(<App />);
}); });
runBasicTests(); runBasicTests();
it('loads dashboard', () => { it('loads dashboard', () => {
const dashboard = screen.getByText('Dashboard'); const main = el.instance.findByType('main')[0];
expect(dashboard).toBeInTheDocument(); expect(main.children.length).toEqual(1);
const dashboard = main.children[0];
expect(dashboard.type).toEqual('Dashboard');
expect(
dashboard.matches(shallow(<Dashboard />)),
).toEqual(true);
}); });
}); });
describe('initialize failure', () => { describe('initialize failure', () => {
beforeEach(() => { beforeAll(() => {
jest.clearAllMocks();
reduxHooks.useRequestIsFailed.mockImplementation((key) => key === RequestKeys.initialize); reduxHooks.useRequestIsFailed.mockImplementation((key) => key === RequestKeys.initialize);
getConfig.mockReturnValue({}); getConfig.mockReturnValue({});
render(<IntlProvider locale="en" messages={messages}><App /></IntlProvider>); el = shallow(<App />);
}); });
runBasicTests(); runBasicTests();
it('loads error page', () => { it('loads error page', () => {
const alert = screen.getByRole('alert'); const main = el.instance.findByType('main')[0];
expect(alert).toBeInTheDocument(); expect(main.children.length).toEqual(1);
const errorPage = screen.getByText('ErrorPage'); const alert = main.children[0];
expect(errorPage).toBeInTheDocument(); expect(alert.type).toEqual('Alert');
expect(alert.children.length).toEqual(1);
const errorPage = alert.children[0];
expect(errorPage.type).toEqual('ErrorPage');
expect(errorPage.props.message).toEqual(formatMessage(messages.errorMessage, { supportEmail }));
}); });
}); });
describe('refresh failure', () => { describe('refresh failure', () => {
beforeEach(() => { beforeAll(() => {
reduxHooks.useRequestIsFailed.mockImplementation((key) => key === RequestKeys.refreshList); reduxHooks.useRequestIsFailed.mockImplementation((key) => key === RequestKeys.refreshList);
getConfig.mockReturnValue({}); getConfig.mockReturnValue({});
render(<IntlProvider locale="en"><App /></IntlProvider>); el = shallow(<App />);
}); });
runBasicTests(); runBasicTests();
it('loads error page', () => { it('loads error page', () => {
const alert = screen.getByRole('alert'); const main = el.instance.findByType('main')[0];
expect(alert).toBeInTheDocument(); expect(main.children.length).toEqual(1);
const errorPage = screen.getByText('ErrorPage'); const alert = main.children[0];
expect(errorPage).toBeInTheDocument(); expect(alert.type).toEqual('Alert');
expect(alert.children.length).toEqual(1);
const errorPage = alert.children[0];
expect(errorPage.type).toEqual('ErrorPage');
expect(errorPage.props.message).toEqual(formatMessage(messages.errorMessage, { supportEmail }));
}); });
}); });
}); });

View File

@@ -0,0 +1,143 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`App router component component initialize failure snapshot 1`] = `
<Fragment>
<HelmetWrapper
defer={true}
encodeSpecialCharacters={true}
>
<title>
Learner Home
</title>
<link
rel="shortcut icon"
type="image/x-icon"
/>
</HelmetWrapper>
<div>
<AppWrapper>
<LearnerDashboardHeader />
<main>
<Alert
variant="danger"
>
<ErrorPage
message="If you experience repeated failures, please email support at test-support-url"
/>
</Alert>
</main>
</AppWrapper>
<FooterSlot />
</div>
</Fragment>
`;
exports[`App router component component no network failure snapshot 1`] = `
<Fragment>
<HelmetWrapper
defer={true}
encodeSpecialCharacters={true}
>
<title>
Learner Home
</title>
<link
rel="shortcut icon"
type="image/x-icon"
/>
</HelmetWrapper>
<div>
<AppWrapper>
<LearnerDashboardHeader />
<main>
<Dashboard />
</main>
</AppWrapper>
<FooterSlot />
</div>
</Fragment>
`;
exports[`App router component component no network failure with optimizely project id snapshot 1`] = `
<Fragment>
<HelmetWrapper
defer={true}
encodeSpecialCharacters={true}
>
<title>
Learner Home
</title>
<link
rel="shortcut icon"
type="image/x-icon"
/>
</HelmetWrapper>
<div>
<AppWrapper>
<LearnerDashboardHeader />
<main>
<Dashboard />
</main>
</AppWrapper>
<FooterSlot />
</div>
</Fragment>
`;
exports[`App router component component no network failure with optimizely url snapshot 1`] = `
<Fragment>
<HelmetWrapper
defer={true}
encodeSpecialCharacters={true}
>
<title>
Learner Home
</title>
<link
rel="shortcut icon"
type="image/x-icon"
/>
</HelmetWrapper>
<div>
<AppWrapper>
<LearnerDashboardHeader />
<main>
<Dashboard />
</main>
</AppWrapper>
<FooterSlot />
</div>
</Fragment>
`;
exports[`App router component component refresh failure snapshot 1`] = `
<Fragment>
<HelmetWrapper
defer={true}
encodeSpecialCharacters={true}
>
<title>
Learner Home
</title>
<link
rel="shortcut icon"
type="image/x-icon"
/>
</HelmetWrapper>
<div>
<AppWrapper>
<LearnerDashboardHeader />
<main>
<Alert
variant="danger"
>
<ErrorPage
message="If you experience repeated failures, please email support at test-support-url"
/>
</Alert>
</main>
</AppWrapper>
<FooterSlot />
</div>
</Fragment>
`;

View File

@@ -0,0 +1,40 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`app registry subscribe: APP_INIT_ERROR. snapshot: displays an ErrorPage to root element 1`] = `
<ErrorPage
message="test-error-message"
/>
`;
exports[`app registry subscribe: APP_READY. links App to root element 1`] = `
<AppProvider
store={
{
"redux": "store",
}
}
wrapWithRouter={true}
>
<NoticesWrapper>
<Routes>
<Route
element={
<PageWrap>
<App />
</PageWrap>
}
path="/"
/>
<Route
element={
<Navigate
replace={true}
to="/"
/>
}
path="*"
/>
</Routes>
</NoticesWrapper>
</AppProvider>
`;

View File

@@ -1,27 +1,27 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import { Alert } from '@openedx/paragon';
import Banner from './Banner'; import Banner from './Banner';
describe('Banner component', () => { describe('Banner', () => {
it('renders children content', () => { const props = {
render(<Banner>Test content</Banner>); children: 'Hello, world!',
expect(screen.getByText('Test content')).toBeInTheDocument(); };
}); describe('snapshot', () => {
test('renders default banner', () => {
const wrapper = shallow(<Banner {...props} />);
expect(wrapper.snapshot).toMatchSnapshot();
});
test('renders with variants', () => {
const wrapper = shallow(<Banner {...props} variant="success" />);
expect(wrapper.snapshot).toMatchSnapshot();
it('uses default props correctly', () => { expect(wrapper.instance.findByType(Alert)[0].props.variant).toEqual('success');
render(<Banner>Test content</Banner>); });
const banner = screen.getByRole('alert'); test('renders with custom class', () => {
expect(banner).toHaveClass('mb-0'); const wrapper = shallow(<Banner {...props} className="custom-class" />);
}); expect(wrapper.snapshot).toMatchSnapshot();
});
it('accepts custom variant prop', () => {
render(<Banner variant="success">Test content</Banner>);
const banner = screen.getByRole('alert');
expect(banner).toHaveClass('alert-success');
});
it('accepts custom className prop', () => {
render(<Banner className="custom-class">Test content</Banner>);
const banner = screen.getByRole('alert');
expect(banner).toHaveClass('custom-class');
}); });
}); });

View File

@@ -3,15 +3,16 @@ import { getAuthenticatedHttpClient, getAuthenticatedUser } from '@edx/frontend-
import { logError, logInfo } from '@edx/frontend-platform/logging'; import { logError, logInfo } from '@edx/frontend-platform/logging';
export const noticesUrl = `${getConfig().LMS_BASE_URL}/notices/api/v1/unacknowledged`; export const noticesUrl = `${getConfig().LMS_BASE_URL}/notices/api/v1/unacknowledged`;
export const error404Message = 'This probably happened because the notices plugin is not installed on platform.';
export const getNotices = ({ onLoad, notFoundMessage }) => { export const getNotices = ({ onLoad }) => {
const authenticatedUser = getAuthenticatedUser(); const authenticatedUser = getAuthenticatedUser();
const handleError = async (e) => { const handleError = async (e) => {
// Error probably means that notices is not installed, which is fine. // Error probably means that notices is not installed, which is fine.
const { customAttributes: { httpErrorStatus } } = e; const { customAttributes: { httpErrorStatus } } = e;
if (httpErrorStatus === 404) { if (httpErrorStatus === 404) {
logInfo(`${e}. ${notFoundMessage}`); logInfo(`${e}. ${error404Message}`);
} else { } else {
logError(e); logError(e);
} }

View File

@@ -1,11 +1,9 @@
import React from 'react'; import React from 'react';
import { getConfig } from '@edx/frontend-platform'; import { getConfig } from '@edx/frontend-platform';
import { useIntl } from '@edx/frontend-platform/i18n';
import { StrictDict } from 'utils'; import { StrictDict } from 'utils';
import { getNotices } from './api'; import { getNotices } from './api';
import * as module from './hooks'; import * as module from './hooks';
import messages from './messages';
/** /**
* This component uses the platform-plugin-notices plugin to function. * This component uses the platform-plugin-notices plugin to function.
@@ -19,8 +17,6 @@ export const state = StrictDict({
export const useNoticesWrapperData = () => { export const useNoticesWrapperData = () => {
const [isRedirected, setIsRedirected] = module.state.isRedirected(); const [isRedirected, setIsRedirected] = module.state.isRedirected();
const { formatMessage } = useIntl();
React.useEffect(() => { React.useEffect(() => {
if (getConfig().ENABLE_NOTICES) { if (getConfig().ENABLE_NOTICES) {
getNotices({ getNotices({
@@ -30,10 +26,9 @@ export const useNoticesWrapperData = () => {
window.location.replace(`${data.data.results[0]}?next=${window.location.href}`); window.location.replace(`${data.data.results[0]}?next=${window.location.href}`);
} }
}, },
notFoundMessage: formatMessage(messages.error404Message),
}); });
} }
}, [setIsRedirected, formatMessage]); }, [setIsRedirected]);
return { isRedirected }; return { isRedirected };
}; };

View File

@@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import { MockUseState, formatMessage } from 'testUtils'; import { MockUseState } from 'testUtils';
import { getConfig } from '@edx/frontend-platform'; import { getConfig } from '@edx/frontend-platform';
import { getNotices } from './api'; import { getNotices } from './api';
@@ -9,22 +9,6 @@ import * as hooks from './hooks';
jest.mock('@edx/frontend-platform', () => ({ getConfig: jest.fn() })); jest.mock('@edx/frontend-platform', () => ({ getConfig: jest.fn() }));
jest.mock('./api', () => ({ getNotices: jest.fn() })); jest.mock('./api', () => ({ getNotices: jest.fn() }));
jest.mock('react', () => ({
...jest.requireActual('react'),
useEffect: jest.fn((cb, prereqs) => ({ useEffect: { cb, prereqs } })),
useContext: jest.fn(context => context),
}));
jest.mock('@edx/frontend-platform/i18n', () => {
const { formatMessage: fn } = jest.requireActual('testUtils');
return {
...jest.requireActual('@edx/frontend-platform/i18n'),
useIntl: () => ({
formatMessage: fn,
}),
};
});
getConfig.mockReturnValue({ ENABLE_NOTICES: true }); getConfig.mockReturnValue({ ENABLE_NOTICES: true });
const state = new MockUseState(hooks); const state = new MockUseState(hooks);
@@ -50,7 +34,7 @@ describe('NoticesWrapper hooks', () => {
getConfig.mockReturnValueOnce({ ENABLE_NOTICES: false }); getConfig.mockReturnValueOnce({ ENABLE_NOTICES: false });
hooks.useNoticesWrapperData(); hooks.useNoticesWrapperData();
const [cb, prereqs] = React.useEffect.mock.calls[0]; const [cb, prereqs] = React.useEffect.mock.calls[0];
expect(prereqs).toEqual([state.setState.isRedirected, formatMessage]); expect(prereqs).toEqual([state.setState.isRedirected]);
cb(); cb();
expect(getNotices).not.toHaveBeenCalled(); expect(getNotices).not.toHaveBeenCalled();
}); });
@@ -59,7 +43,7 @@ describe('NoticesWrapper hooks', () => {
hooks.useNoticesWrapperData(); hooks.useNoticesWrapperData();
expect(React.useEffect).toHaveBeenCalled(); expect(React.useEffect).toHaveBeenCalled();
const [cb, prereqs] = React.useEffect.mock.calls[0]; const [cb, prereqs] = React.useEffect.mock.calls[0];
expect(prereqs).toEqual([state.setState.isRedirected, formatMessage]); expect(prereqs).toEqual([state.setState.isRedirected]);
cb(); cb();
expect(getNotices).toHaveBeenCalled(); expect(getNotices).toHaveBeenCalled();
const { onLoad } = getNotices.mock.calls[0][0]; const { onLoad } = getNotices.mock.calls[0][0];
@@ -75,7 +59,7 @@ describe('NoticesWrapper hooks', () => {
window.location = { replace: jest.fn(), href: 'test-old-href' }; window.location = { replace: jest.fn(), href: 'test-old-href' };
hooks.useNoticesWrapperData(); hooks.useNoticesWrapperData();
const [cb, prereqs] = React.useEffect.mock.calls[0]; const [cb, prereqs] = React.useEffect.mock.calls[0];
expect(prereqs).toEqual([state.setState.isRedirected, formatMessage]); expect(prereqs).toEqual([state.setState.isRedirected]);
cb(); cb();
expect(getNotices).toHaveBeenCalled(); expect(getNotices).toHaveBeenCalled();
const { onLoad } = getNotices.mock.calls[0][0]; const { onLoad } = getNotices.mock.calls[0][0];

View File

@@ -1,4 +1,5 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import { shallow } from '@edx/react-unit-test-utils';
import useNoticesWrapperData from './hooks'; import useNoticesWrapperData from './hooks';
import NoticesWrapper from '.'; import NoticesWrapper from '.';
@@ -6,31 +7,30 @@ import NoticesWrapper from '.';
jest.mock('./hooks', () => jest.fn()); jest.mock('./hooks', () => jest.fn());
const hookProps = { isRedirected: false }; const hookProps = { isRedirected: false };
useNoticesWrapperData.mockReturnValue(hookProps);
let el;
const children = [<b key={1}>some</b>, <i key={2}>children</i>]; const children = [<b key={1}>some</b>, <i key={2}>children</i>];
describe('NoticesWrapper component', () => { describe('NoticesWrapper component', () => {
beforeEach(() => {
useNoticesWrapperData.mockClear();
});
describe('behavior', () => { describe('behavior', () => {
it('initializes hooks', () => { it('initializes hooks', () => {
useNoticesWrapperData.mockReturnValue(hookProps); el = shallow(<NoticesWrapper>{children}</NoticesWrapper>);
render(<NoticesWrapper>{children}</NoticesWrapper>);
expect(useNoticesWrapperData).toHaveBeenCalledWith(); expect(useNoticesWrapperData).toHaveBeenCalledWith();
}); });
}); });
describe('output', () => { describe('output', () => {
it('does not show children if redirected', () => { it('does not show children if redirected', () => {
useNoticesWrapperData.mockReturnValueOnce({ isRedirected: true }); useNoticesWrapperData.mockReturnValueOnce({ isRedirected: true });
render(<NoticesWrapper>{children}</NoticesWrapper>); el = shallow(<NoticesWrapper>{children}</NoticesWrapper>);
expect(screen.queryByText('some')).not.toBeInTheDocument(); expect(el.instance.children.length).toEqual(0);
expect(screen.queryByText('children')).not.toBeInTheDocument();
}); });
it('shows children if not redirected', () => { it('shows children if not redirected', () => {
useNoticesWrapperData.mockReturnValue(hookProps); el = shallow(<NoticesWrapper>{children}</NoticesWrapper>);
render(<NoticesWrapper>{children}</NoticesWrapper>); expect(el.instance.children.length).toEqual(2);
expect(screen.getByText('some')).toBeInTheDocument(); expect(el.instance.children[0].type).toEqual(shallow(children[0]).type);
expect(screen.getByText('children')).toBeInTheDocument(); expect(el.instance.props).toEqual(shallow(children[0]).props);
expect(el.instance.children[1].type).toEqual(shallow(children[1]).type);
expect(el.instance.props).toEqual(shallow(children[1]).props);
}); });
}); });
}); });

View File

@@ -1,11 +0,0 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({
error404Message: {
id: 'learner-dash.notices.error404Message',
defaultMessage: 'This probably happened because the notices plugin is not installed on platform.',
description: 'Error message when notices API returns 404',
},
});
export default messages;

View File

@@ -0,0 +1,65 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ZendeskFab snapshot 1`] = `
<Zendesk
cookies={true}
defer={true}
webWidget={
{
"answerBot": {
"avatar": {
"name": {
"*": "edX Support",
},
"url": "https://edx-cdn.org/v3/prod/favicon.ico",
},
"contactOnlyAfterQuery": true,
"suppress": false,
"title": {
"*": "edX Support",
},
},
"chat": {
"departments": {
"enabled": [
"account settings",
"billing and payments",
"certificates",
"deadlines",
"errors and technical issues",
"other",
"proctoring",
],
},
"suppress": false,
},
"contactForm": {
"attachments": true,
"selectTicketForm": {
"*": "Please choose your request type:",
},
"ticketForms": [
{
"fields": [
{
"id": "description",
"prefill": {
"*": "",
},
},
],
"id": 360003368814,
"subject": false,
},
],
},
"contactOptions": {
"enabled": false,
},
"helpCenter": {
"originalArticleButton": true,
},
}
}
/>
`;

View File

@@ -0,0 +1,56 @@
import React from 'react';
import { getConfig } from '@edx/frontend-platform';
import { useIntl } from '@edx/frontend-platform/i18n';
import Zendesk from 'react-zendesk';
import messages from './messages';
const ZendeskFab = () => {
const { formatMessage } = useIntl();
const setting = {
cookies: true,
webWidget: {
contactOptions: {
enabled: false,
},
chat: {
suppress: false,
departments: {
enabled: ['account settings', 'billing and payments', 'certificates', 'deadlines', 'errors and technical issues', 'other', 'proctoring'],
},
},
contactForm: {
ticketForms: [
{
id: 360003368814,
subject: false,
fields: [{ id: 'description', prefill: { '*': '' } }],
},
],
selectTicketForm: {
'*': formatMessage(messages.selectTicketForm),
},
attachments: true,
},
helpCenter: {
originalArticleButton: true,
},
answerBot: {
suppress: false,
contactOnlyAfterQuery: true,
title: { '*': formatMessage(messages.supportTitle) },
avatar: {
url: 'https://edx-cdn.org/v3/prod/favicon.ico',
name: { '*': formatMessage(messages.supportTitle) },
},
},
},
};
return (
<Zendesk defer zendeskKey={getConfig().ZENDESK_KEY} {...setting} />
);
};
export default ZendeskFab;

View File

@@ -0,0 +1,12 @@
import { shallow } from '@edx/react-unit-test-utils';
import ZendeskFab from '.';
jest.mock('react-zendesk', () => 'Zendesk');
describe('ZendeskFab', () => {
test('snapshot', () => {
const wrapper = shallow(<ZendeskFab />);
expect(wrapper.snapshot).toMatchSnapshot();
});
});

View File

@@ -0,0 +1,16 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({
supportTitle: {
id: 'zendesk.supportTitle',
description: 'Title for the support button',
defaultMessage: 'edX Support',
},
selectTicketForm: {
id: 'zendesk.selectTicketForm',
description: 'Select ticket form',
defaultMessage: 'Please choose your request type:',
},
});
export default messages;

View File

@@ -0,0 +1,31 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Banner snapshot renders default banner 1`] = `
<Alert
className="mb-0"
icon={[MockFunction icons.Info]}
variant="info"
>
Hello, world!
</Alert>
`;
exports[`Banner snapshot renders with custom class 1`] = `
<Alert
className="custom-class"
icon={[MockFunction icons.Info]}
variant="info"
>
Hello, world!
</Alert>
`;
exports[`Banner snapshot renders with variants 1`] = `
<Alert
className="mb-0"
icon={[MockFunction icons.Info]}
variant="success"
>
Hello, world!
</Alert>
`;

View File

@@ -2,7 +2,6 @@ const configuration = {
// BASE_URL: process.env.BASE_URL, // BASE_URL: process.env.BASE_URL,
LMS_BASE_URL: process.env.LMS_BASE_URL, LMS_BASE_URL: process.env.LMS_BASE_URL,
ECOMMERCE_BASE_URL: process.env.ECOMMERCE_BASE_URL, ECOMMERCE_BASE_URL: process.env.ECOMMERCE_BASE_URL,
CREDIT_PURCHASE_URL: process.env.CREDIT_PURCHASE_URL,
// LOGIN_URL: process.env.LOGIN_URL, // LOGIN_URL: process.env.LOGIN_URL,
// LOGOUT_URL: process.env.LOGOUT_URL, // LOGOUT_URL: process.env.LOGOUT_URL,
// CSRF_TOKEN_API_PATH: process.env.CSRF_TOKEN_API_PATH, // CSRF_TOKEN_API_PATH: process.env.CSRF_TOKEN_API_PATH,
@@ -13,6 +12,7 @@ const configuration = {
// ACCESS_TOKEN_COOKIE_NAME: process.env.ACCESS_TOKEN_COOKIE_NAME, // ACCESS_TOKEN_COOKIE_NAME: process.env.ACCESS_TOKEN_COOKIE_NAME,
LEARNING_BASE_URL: process.env.LEARNING_BASE_URL, LEARNING_BASE_URL: process.env.LEARNING_BASE_URL,
SESSION_COOKIE_DOMAIN: process.env.SESSION_COOKIE_DOMAIN || '', SESSION_COOKIE_DOMAIN: process.env.SESSION_COOKIE_DOMAIN || '',
ZENDESK_KEY: process.env.ZENDESK_KEY,
SUPPORT_URL: process.env.SUPPORT_URL || null, SUPPORT_URL: process.env.SUPPORT_URL || null,
ENABLE_NOTICES: process.env.ENABLE_NOTICES || null, ENABLE_NOTICES: process.env.ENABLE_NOTICES || null,
CAREER_LINK_URL: process.env.CAREER_LINK_URL || null, CAREER_LINK_URL: process.env.CAREER_LINK_URL || null,
@@ -20,7 +20,6 @@ const configuration = {
ENABLE_EDX_PERSONAL_DASHBOARD: process.env.ENABLE_EDX_PERSONAL_DASHBOARD === 'true', ENABLE_EDX_PERSONAL_DASHBOARD: process.env.ENABLE_EDX_PERSONAL_DASHBOARD === 'true',
SEARCH_CATALOG_URL: process.env.SEARCH_CATALOG_URL || null, SEARCH_CATALOG_URL: process.env.SEARCH_CATALOG_URL || null,
ENABLE_PROGRAMS: process.env.ENABLE_PROGRAMS === 'true', ENABLE_PROGRAMS: process.env.ENABLE_PROGRAMS === 'true',
NON_BROWSABLE_COURSES: process.env.NON_BROWSABLE_COURSES === 'true',
}; };
const features = {}; const features = {};

View File

@@ -1,8 +1,10 @@
@import "@openedx/paragon/scss/core/core";
.course-card { .course-card {
.card { .card {
.pgn__card-wrapper-image-cap.vertical { .pgn__card-wrapper-image-cap.vertical {
display: flex; display: flex;
min-height: var(--pgn-size-card-image-vertical-max-height); min-height: $card-image-vertical-max-height;
} }
.pgn__card-image-cap { .pgn__card-image-cap {
border-bottom-left-radius: 0 !important; border-bottom-left-radius: 0 !important;
@@ -51,11 +53,11 @@
> .alert { > .alert {
border-radius: 0; border-radius: 0;
box-shadow: none; box-shadow: none;
padding: var(--pgn-spacing-spacer-3) var(--pgn-spacing-spacer-4); padding: map-get($spacers, 3) map-get($spacers, 4);
&:last-of-type { &:last-of-type {
border-bottom-left-radius: var(--pgn-size-alert-border-radius); border-bottom-left-radius: $alert-border-radius;
border-bottom-right-radius: var(--pgn-size-alert-border-radius); border-bottom-right-radius: $alert-border-radius;
} }
} }

View File

@@ -0,0 +1,111 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`CourseCard component snapshot: collapsed 1`] = `
<div
className="mb-4.5 course-card"
data-testid="CourseCard"
id="test-card-id"
>
<Card
orientation="vertical"
>
<div
className="d-flex flex-column w-100"
>
<div>
<CourseCardImage
cardId="test-card-id"
orientation="horizontal"
/>
<Card.Body>
<Card.Header
actions={
<CourseCardMenu
cardId="test-card-id"
/>
}
title={
<CourseCardTitle
cardId="test-card-id"
/>
}
/>
<Card.Section
className="pt-0"
>
<CourseCardDetails
cardId="test-card-id"
/>
</Card.Section>
<Card.Footer
orientation="vertical"
>
<CourseCardActions
cardId="test-card-id"
/>
</Card.Footer>
</Card.Body>
</div>
<CourseCardBanners
cardId="test-card-id"
/>
</div>
</Card>
</div>
`;
exports[`CourseCard component snapshot: not collapsed 1`] = `
<div
className="mb-4.5 course-card"
data-testid="CourseCard"
id="test-card-id"
>
<Card
orientation="horizontal"
>
<div
className="d-flex flex-column w-100"
>
<div
className="d-flex"
>
<CourseCardImage
cardId="test-card-id"
orientation="horizontal"
/>
<Card.Body>
<Card.Header
actions={
<CourseCardMenu
cardId="test-card-id"
/>
}
title={
<CourseCardTitle
cardId="test-card-id"
/>
}
/>
<Card.Section
className="pt-0"
>
<CourseCardDetails
cardId="test-card-id"
/>
</Card.Section>
<Card.Footer
orientation="horizontal"
>
<CourseCardActions
cardId="test-card-id"
/>
</Card.Footer>
</Card.Body>
</div>
<CourseCardBanners
cardId="test-card-id"
/>
</div>
</Card>
</div>
`;

View File

@@ -0,0 +1,14 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ActionButton snapshot is collapsed 1`] = `
<Button
arbitary="props"
size="sm"
/>
`;
exports[`ActionButton snapshot is not collapsed 1`] = `
<Button
arbitary="props"
/>
`;

View File

@@ -1,33 +1,6 @@
import { useWindowSize, breakpoints } from '@openedx/paragon'; import { useWindowSize, breakpoints } from '@openedx/paragon';
import useIsCollapsed from './hooks'; import useIsCollapsed from './hooks';
jest.mock('@openedx/paragon', () => ({
...jest.requireActual('@openedx/paragon'),
useWindowSize: jest.fn(),
breakpoints: {
extraSmall: {
minWidth: 0,
maxWidth: 575,
},
small: {
minWidth: 576,
maxWidth: 767,
},
medium: {
minWidth: 768,
maxWidth: 991,
},
large: {
minWidth: 992,
maxWidth: 1199,
},
extraLarge: {
minWidth: 1200,
maxWidth: 100000,
},
},
}));
describe('useIsCollapsed', () => { describe('useIsCollapsed', () => {
it('returns true only when it is between medium and small', () => { it('returns true only when it is between medium and small', () => {
// make sure all three breakpoints gap is large enough for test // make sure all three breakpoints gap is large enough for test

View File

@@ -1,4 +1,5 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import ActionButton from '.'; import ActionButton from '.';
import useIsCollapsed from './hooks'; import useIsCollapsed from './hooks';
@@ -7,22 +8,18 @@ jest.mock('./hooks', () => jest.fn());
describe('ActionButton', () => { describe('ActionButton', () => {
const props = { const props = {
className: 'custom-class', arbitary: 'props',
children: 'Test',
}; };
describe('snapshot', () => {
it('is collapsed', async () => { test('is collapsed', () => {
useIsCollapsed.mockReturnValue(true); useIsCollapsed.mockReturnValueOnce(true);
render(<ActionButton {...props} />); const wrapper = shallow(<ActionButton {...props} />);
const button = screen.getByRole('button', { name: 'Test' }); expect(wrapper.snapshot).toMatchSnapshot();
expect(button).toHaveClass('btn-sm', 'custom-class'); });
}); test('is not collapsed', () => {
useIsCollapsed.mockReturnValueOnce(false);
it('is not collapsed', () => { const wrapper = shallow(<ActionButton {...props} />);
useIsCollapsed.mockReturnValue(false); expect(wrapper.snapshot).toMatchSnapshot();
render(<ActionButton {...props} />); });
const button = screen.getByRole('button', { name: 'Test' });
expect(button).toBeInTheDocument();
expect(button).not.toHaveClass('size', 'sm');
}); });
}); });

View File

@@ -1,6 +1,5 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import userEvent from '@testing-library/user-event';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import track from 'tracking'; import track from 'tracking';
import useActionDisabledState from '../hooks'; import useActionDisabledState from '../hooks';
@@ -19,70 +18,68 @@ jest.mock('hooks', () => ({
useTrackCourseEvent: jest.fn(), useTrackCourseEvent: jest.fn(),
}, },
})); }));
jest.mock('../hooks', () => jest.fn(() => ({ disableBeginCourse: false }))); jest.mock('../hooks', () => jest.fn(() => ({ disableBeginCourse: false })));
jest.mock('./ActionButton', () => 'ActionButton');
jest.mock('./ActionButton/hooks', () => jest.fn(() => false)); let wrapper;
const homeUrl = 'home-url'; const homeUrl = 'home-url';
reduxHooks.useCardCourseRunData.mockReturnValue({ homeUrl }); reduxHooks.useCardCourseRunData.mockReturnValue({ homeUrl });
const execEdPath = (cardId) => `exec-ed-tracking-path=${cardId}`; const execEdPath = (cardId) => `exec-ed-tracking-path=${cardId}`;
reduxHooks.useCardExecEdTrackingParam.mockImplementation(execEdPath); reduxHooks.useCardExecEdTrackingParam.mockImplementation(execEdPath);
reduxHooks.useTrackCourseEvent.mockImplementation( reduxHooks.useTrackCourseEvent.mockImplementation(
(eventName, cardId, url) => ({ trackCourseEvent: { eventName, cardId, url } }), (eventName, cardId, upgradeUrl) => ({ trackCourseEvent: { eventName, cardId, upgradeUrl } }),
); );
const props = {
cardId: 'cardId',
};
const renderComponent = () => render(<IntlProvider locale="en"><BeginCourseButton {...props} /></IntlProvider>);
describe('BeginCourseButton', () => { describe('BeginCourseButton', () => {
const props = {
cardId: 'cardId',
};
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
describe('initiliaze hooks', () => { describe('behavior', () => {
it('initializes course run data with cardId', () => { it('initializes course run data with cardId', () => {
renderComponent(); wrapper = shallow(<BeginCourseButton {...props} />);
expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(props.cardId); expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(props.cardId);
}); });
it('loads exec education path param', () => { it('loads exec education path param', () => {
renderComponent(); wrapper = shallow(<BeginCourseButton {...props} />);
expect(reduxHooks.useCardExecEdTrackingParam).toHaveBeenCalledWith(props.cardId); expect(reduxHooks.useCardExecEdTrackingParam).toHaveBeenCalledWith(props.cardId);
}); });
it('loads disabled states for begin action from action hooks', () => { it('loads disabled states for begin action from action hooks', () => {
renderComponent(); wrapper = shallow(<BeginCourseButton {...props} />);
expect(useActionDisabledState).toHaveBeenCalledWith(props.cardId); expect(useActionDisabledState).toHaveBeenCalledWith(props.cardId);
}); });
}); });
describe('behavior', () => { describe('snapshot', () => {
describe('disabled', () => { describe('disabled', () => {
it('should be disabled', () => { beforeEach(() => {
useActionDisabledState.mockReturnValueOnce({ disableBeginCourse: true }); useActionDisabledState.mockReturnValueOnce({ disableBeginCourse: true });
renderComponent(); wrapper = shallow(<BeginCourseButton {...props} />);
const button = screen.getByRole('button', { name: 'Begin Course' }); });
expect(button).toHaveClass('disabled'); test('snapshot', () => {
expect(button).toHaveAttribute('aria-disabled', 'true'); expect(wrapper.snapshot).toMatchSnapshot();
});
it('should be disabled', () => {
expect(wrapper.instance.props.disabled).toEqual(true);
}); });
}); });
describe('enabled', () => { describe('enabled', () => {
it('should be enabled', () => { beforeEach(() => {
renderComponent(); wrapper = shallow(<BeginCourseButton {...props} />);
const button = screen.getByRole('button', { name: 'Begin Course' });
expect(button).not.toHaveClass('disabled');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
}); });
it('should track enter course clicked event on click, with exec ed param', async () => { test('snapshot', () => {
renderComponent(); expect(wrapper.snapshot).toMatchSnapshot();
const user = userEvent.setup(); });
const button = screen.getByRole('button', { name: 'Begin Course' }); it('should be enabled', () => {
user.click(button); expect(wrapper.instance.props.disabled).toEqual(false);
expect(reduxHooks.useTrackCourseEvent).toHaveBeenCalledWith( });
it('should track enter course clicked event on click, with exec ed param', () => {
expect(wrapper.instance.props.onClick).toEqual(reduxHooks.useTrackCourseEvent(
track.course.enterCourseClicked, track.course.enterCourseClicked,
props.cardId, props.cardId,
homeUrl + execEdPath(props.cardId), homeUrl + execEdPath(props.cardId),
); ));
}); });
}); });
}); });

View File

@@ -1,6 +1,4 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import userEvent from '@testing-library/user-event';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import track from 'tracking'; import track from 'tracking';
@@ -21,63 +19,65 @@ jest.mock('hooks', () => ({
}, },
})); }));
jest.mock('../hooks', () => jest.fn(() => ({ disableResumeCourse: false }))); jest.mock('../hooks', () => jest.fn(() => ({ disableResumeCourse: false })));
jest.mock('./ActionButton', () => 'ActionButton');
jest.mock('./ActionButton/hooks', () => jest.fn(() => false));
const resumeUrl = 'resume-url'; const resumeUrl = 'resume-url';
reduxHooks.useCardCourseRunData.mockReturnValue({ resumeUrl }); reduxHooks.useCardCourseRunData.mockReturnValue({ resumeUrl });
const execEdPath = (cardId) => `exec-ed-tracking-path=${cardId}`; const execEdPath = (cardId) => `exec-ed-tracking-path=${cardId}`;
reduxHooks.useCardExecEdTrackingParam.mockImplementation(execEdPath); reduxHooks.useCardExecEdTrackingParam.mockImplementation(execEdPath);
reduxHooks.useTrackCourseEvent.mockImplementation( reduxHooks.useTrackCourseEvent.mockImplementation(
(eventName, cardId, url) => ({ trackCourseEvent: { eventName, cardId, url } }), (eventName, cardId, upgradeUrl) => ({ trackCourseEvent: { eventName, cardId, upgradeUrl } }),
); );
let wrapper;
describe('ResumeButton', () => { describe('ResumeButton', () => {
const props = { const props = {
cardId: 'cardId', cardId: 'cardId',
}; };
describe('initialize hooks', () => { describe('behavior', () => {
beforeEach(() => render(<IntlProvider locale="en"><ResumeButton {...props} /></IntlProvider>));
it('initializes course run data with cardId', () => { it('initializes course run data with cardId', () => {
wrapper = shallow(<ResumeButton {...props} />);
expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(props.cardId); expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(props.cardId);
}); });
it('loads exec education path param', () => { it('loads exec education path param', () => {
wrapper = shallow(<ResumeButton {...props} />);
expect(reduxHooks.useCardExecEdTrackingParam).toHaveBeenCalledWith(props.cardId); expect(reduxHooks.useCardExecEdTrackingParam).toHaveBeenCalledWith(props.cardId);
}); });
it('loads disabled states for resume action from action hooks', () => { it('loads disabled states for resume action from action hooks', () => {
wrapper = shallow(<ResumeButton {...props} />);
expect(useActionDisabledState).toHaveBeenCalledWith(props.cardId); expect(useActionDisabledState).toHaveBeenCalledWith(props.cardId);
}); });
}); });
describe('behavior', () => { describe('snapshot', () => {
describe('disabled', () => { describe('disabled', () => {
beforeEach(() => { beforeEach(() => {
useActionDisabledState.mockReturnValueOnce({ disableResumeCourse: true }); useActionDisabledState.mockReturnValueOnce({ disableResumeCourse: true });
wrapper = shallow(<ResumeButton {...props} />);
});
test('snapshot', () => {
expect(wrapper.snapshot).toMatchSnapshot();
}); });
it('should be disabled', () => { it('should be disabled', () => {
render(<IntlProvider locale="en"><ResumeButton {...props} /></IntlProvider>); expect(wrapper.instance.props.disabled).toEqual(true);
const button = screen.getByRole('button', { name: 'Resume' });
expect(button).toHaveClass('disabled');
expect(button).toHaveAttribute('aria-disabled', 'true');
}); });
}); });
describe('enabled', () => { describe('enabled', () => {
it('should be enabled', () => { beforeEach(() => {
render(<IntlProvider locale="en"><ResumeButton {...props} /></IntlProvider>); wrapper = shallow(<ResumeButton {...props} />);
const button = screen.getByRole('button', { name: 'Resume' });
expect(button).toBeInTheDocument();
expect(button).not.toHaveClass('disabled');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
}); });
it('should track enter course clicked event on click, with exec ed param', async () => { test('snapshot', () => {
render(<IntlProvider locale="en"><ResumeButton {...props} /></IntlProvider>); expect(wrapper.snapshot).toMatchSnapshot();
const user = userEvent.setup(); });
const button = screen.getByRole('button', { name: 'Resume' }); it('should be enabled', () => {
user.click(button); expect(wrapper.instance.props.disabled).toEqual(false);
expect(reduxHooks.useTrackCourseEvent).toHaveBeenCalledWith( });
it('should track enter course clicked event on click, with exec ed param', () => {
expect(wrapper.instance.props.onClick).toEqual(reduxHooks.useTrackCourseEvent(
track.course.enterCourseClicked, track.course.enterCourseClicked,
props.cardId, props.cardId,
resumeUrl + execEdPath(props.cardId), resumeUrl + execEdPath(props.cardId),
); ));
}); });
}); });
}); });

View File

@@ -1,6 +1,4 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import userEvent from '@testing-library/user-event';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import useActionDisabledState from '../hooks'; import useActionDisabledState from '../hooks';
@@ -9,35 +7,28 @@ import SelectSessionButton from './SelectSessionButton';
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
reduxHooks: { reduxHooks: {
useUpdateSelectSessionModalCallback: jest.fn(), useUpdateSelectSessionModalCallback: () => jest.fn().mockName('mockOpenSessionModal'),
}, },
})); }));
jest.mock('../hooks', () => jest.fn(() => ({ disableSelectSession: false }))); jest.mock('../hooks', () => jest.fn(() => ({ disableSelectSession: false })));
jest.mock('./ActionButton', () => 'ActionButton');
jest.mock('./ActionButton/hooks', () => jest.fn(() => false)); let wrapper;
describe('SelectSessionButton', () => { describe('SelectSessionButton', () => {
const props = { cardId: 'cardId' }; const props = { cardId: 'cardId' };
it('default render', () => { it('default render', () => {
render(<IntlProvider locale="en"><SelectSessionButton {...props} /></IntlProvider>); wrapper = shallow(<SelectSessionButton {...props} />);
const button = screen.getByRole('button', { name: 'Select Session' }); expect(wrapper.snapshot).toMatchSnapshot();
expect(button).toBeInTheDocument(); expect(wrapper.instance.props.disabled).toEqual(false);
expect(wrapper.instance.props.onClick.getMockName()).toEqual(
reduxHooks.useUpdateSelectSessionModalCallback().getMockName(),
);
}); });
describe('if useActionDisabledState is false', () => { test('disabled states', () => {
it('should disabled Select Session', () => { useActionDisabledState.mockReturnValueOnce({ disableSelectSession: true });
useActionDisabledState.mockReturnValueOnce({ disableSelectSession: true }); wrapper = shallow(<SelectSessionButton {...props} />);
render(<IntlProvider locale="en"><SelectSessionButton {...props} /></IntlProvider>); expect(wrapper.snapshot).toMatchSnapshot();
const button = screen.getByRole('button', { name: 'Select Session' }); expect(wrapper.instance.props.disabled).toEqual(true);
expect(button).toBeDisabled();
});
});
describe('on click', () => {
it('should call openSessionModal', async () => {
render(<IntlProvider locale="en"><SelectSessionButton {...props} /></IntlProvider>);
const user = userEvent.setup();
const button = screen.getByRole('button', { name: 'Select Session' });
await user.click(button);
expect(reduxHooks.useUpdateSelectSessionModalCallback).toHaveBeenCalledWith(props.cardId);
});
}); });
}); });

View File

@@ -0,0 +1,45 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Locked } from '@openedx/paragon/icons';
import { useIntl } from '@edx/frontend-platform/i18n';
import track from 'tracking';
import { reduxHooks } from 'hooks';
import useActionDisabledState from '../hooks';
import ActionButton from './ActionButton';
import messages from './messages';
export const UpgradeButton = ({ cardId }) => {
const { formatMessage } = useIntl();
const { upgradeUrl } = reduxHooks.useCardCourseRunData(cardId);
const { disableUpgradeCourse } = useActionDisabledState(cardId);
const trackUpgradeClick = reduxHooks.useTrackCourseEvent(
track.course.upgradeClicked,
cardId,
upgradeUrl,
);
const enabledProps = {
as: 'a',
href: upgradeUrl,
onClick: trackUpgradeClick,
};
return (
<ActionButton
iconBefore={Locked}
variant="outline-primary"
disabled={disableUpgradeCourse}
{...!disableUpgradeCourse && enabledProps}
>
{formatMessage(messages.upgrade)}
</ActionButton>
);
};
UpgradeButton.propTypes = {
cardId: PropTypes.string.isRequired,
};
export default UpgradeButton;

View File

@@ -0,0 +1,49 @@
import { shallow } from '@edx/react-unit-test-utils';
import track from 'tracking';
import { reduxHooks } from 'hooks';
import useActionDisabledState from '../hooks';
import UpgradeButton from './UpgradeButton';
jest.mock('tracking', () => ({
course: {
upgradeClicked: jest.fn().mockName('segment.trackUpgradeClicked'),
},
}));
jest.mock('hooks', () => ({
reduxHooks: {
useCardCourseRunData: jest.fn(),
useTrackCourseEvent: jest.fn(
(eventName, cardId, upgradeUrl) => ({ trackCourseEvent: { eventName, cardId, upgradeUrl } }),
),
},
}));
jest.mock('../hooks', () => jest.fn(() => ({ disableUpgradeCourse: false })));
jest.mock('./ActionButton', () => 'ActionButton');
describe('UpgradeButton', () => {
const props = {
cardId: 'cardId',
};
const upgradeUrl = 'upgradeUrl';
reduxHooks.useCardCourseRunData.mockReturnValue({ upgradeUrl });
describe('snapshot', () => {
test('can upgrade', () => {
const wrapper = shallow(<UpgradeButton {...props} />);
expect(wrapper.snapshot).toMatchSnapshot();
expect(wrapper.instance.props.disabled).toEqual(false);
expect(wrapper.instance.props.onClick).toEqual(reduxHooks.useTrackCourseEvent(
track.course.upgradeClicked,
props.cardId,
upgradeUrl,
));
});
test('cannot upgrade', () => {
useActionDisabledState.mockReturnValueOnce({ disableUpgradeCourse: true });
const wrapper = shallow(<UpgradeButton {...props} />);
expect(wrapper.snapshot).toMatchSnapshot();
expect(wrapper.instance.props.disabled).toEqual(true);
});
});
});

View File

@@ -1,6 +1,4 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import userEvent from '@testing-library/user-event';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import track from 'tracking'; import track from 'tracking';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
@@ -16,40 +14,32 @@ jest.mock('tracking', () => ({
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
reduxHooks: { reduxHooks: {
useCardCourseRunData: jest.fn(() => ({ homeUrl: 'homeUrl' })), useCardCourseRunData: jest.fn(() => ({ homeUrl: 'homeUrl' })),
useTrackCourseEvent: jest.fn(), useTrackCourseEvent: jest.fn(
(eventName, cardId, upgradeUrl) => ({ trackCourseEvent: { eventName, cardId, upgradeUrl } }),
),
}, },
})); }));
jest.mock('../hooks', () => jest.fn(() => ({ disableViewCourse: false }))); jest.mock('../hooks', () => jest.fn(() => ({ disableViewCourse: false })));
jest.mock('./ActionButton', () => 'ActionButton');
jest.mock('./ActionButton/hooks', () => jest.fn(() => false));
const defaultProps = { cardId: 'cardId' }; const defaultProps = { cardId: 'cardId' };
const homeUrl = 'homeUrl'; const homeUrl = 'homeUrl';
describe('ViewCourseButton', () => { describe('ViewCourseButton', () => {
it('learner can view course', async () => { test('learner can view course', () => {
render(<IntlProvider locale="en"><ViewCourseButton {...defaultProps} /></IntlProvider>); const wrapper = shallow(<ViewCourseButton {...defaultProps} />);
const button = screen.getByRole('button', { name: 'View Course' }); expect(wrapper.snapshot).toMatchSnapshot();
expect(button).toBeInTheDocument(); expect(wrapper.instance.props.onClick).toEqual(reduxHooks.useTrackCourseEvent(
expect(button).not.toHaveClass('disabled');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
});
it('calls trackCourseEvent on click', async () => {
render(<IntlProvider locale="en"><ViewCourseButton {...defaultProps} /></IntlProvider>);
const user = userEvent.setup();
const button = screen.getByRole('button', { name: 'View Course' });
await user.click(button);
expect(reduxHooks.useTrackCourseEvent).toHaveBeenCalledWith(
track.course.enterCourseClicked, track.course.enterCourseClicked,
defaultProps.cardId, defaultProps.cardId,
homeUrl, homeUrl,
); ));
expect(wrapper.instance.props.disabled).toEqual(false);
}); });
it('learner cannot view course', () => { test('learner cannot view course', () => {
useActionDisabledState.mockReturnValueOnce({ disableViewCourse: true }); useActionDisabledState.mockReturnValueOnce({ disableViewCourse: true });
render(<IntlProvider locale="en"><ViewCourseButton {...defaultProps} /></IntlProvider>); const wrapper = shallow(<ViewCourseButton {...defaultProps} />);
const button = screen.getByRole('button', { name: 'View Course' }); expect(wrapper.snapshot).toMatchSnapshot();
expect(button).toHaveClass('disabled'); expect(wrapper.instance.props.disabled).toEqual(true);
expect(button).toHaveAttribute('aria-disabled', 'true');
}); });
}); });

View File

@@ -0,0 +1,39 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`BeginCourseButton snapshot disabled snapshot 1`] = `
<ActionButton
as="a"
disabled={true}
href="#"
onClick={
{
"trackCourseEvent": {
"cardId": "cardId",
"eventName": [MockFunction segment.enterCourseClicked],
"upgradeUrl": "home-urlexec-ed-tracking-path=cardId",
},
}
}
>
Begin Course
</ActionButton>
`;
exports[`BeginCourseButton snapshot enabled snapshot 1`] = `
<ActionButton
as="a"
disabled={false}
href="#"
onClick={
{
"trackCourseEvent": {
"cardId": "cardId",
"eventName": [MockFunction segment.enterCourseClicked],
"upgradeUrl": "home-urlexec-ed-tracking-path=cardId",
},
}
}
>
Begin Course
</ActionButton>
`;

View File

@@ -0,0 +1,39 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ResumeButton snapshot disabled snapshot 1`] = `
<ActionButton
as="a"
disabled={true}
href="#"
onClick={
{
"trackCourseEvent": {
"cardId": "cardId",
"eventName": [MockFunction segment.enterCourseClicked],
"upgradeUrl": "resume-urlexec-ed-tracking-path=cardId",
},
}
}
>
Resume
</ActionButton>
`;
exports[`ResumeButton snapshot enabled snapshot 1`] = `
<ActionButton
as="a"
disabled={false}
href="#"
onClick={
{
"trackCourseEvent": {
"cardId": "cardId",
"eventName": [MockFunction segment.enterCourseClicked],
"upgradeUrl": "resume-urlexec-ed-tracking-path=cardId",
},
}
}
>
Resume
</ActionButton>
`;

View File

@@ -0,0 +1,19 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`SelectSessionButton default render 1`] = `
<ActionButton
disabled={false}
onClick={[MockFunction mockOpenSessionModal]}
>
Select Session
</ActionButton>
`;
exports[`SelectSessionButton disabled states 1`] = `
<ActionButton
disabled={true}
onClick={[MockFunction mockOpenSessionModal]}
>
Select Session
</ActionButton>
`;

View File

@@ -0,0 +1,32 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`UpgradeButton snapshot can upgrade 1`] = `
<ActionButton
as="a"
disabled={false}
href="upgradeUrl"
iconBefore={[MockFunction icons.Locked]}
onClick={
{
"trackCourseEvent": {
"cardId": "cardId",
"eventName": [MockFunction segment.trackUpgradeClicked],
"upgradeUrl": "upgradeUrl",
},
}
}
variant="outline-primary"
>
Upgrade
</ActionButton>
`;
exports[`UpgradeButton snapshot cannot upgrade 1`] = `
<ActionButton
disabled={true}
iconBefore={[MockFunction icons.Locked]}
variant="outline-primary"
>
Upgrade
</ActionButton>
`;

View File

@@ -0,0 +1,39 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ViewCourseButton learner can view course 1`] = `
<ActionButton
as="a"
disabled={false}
href="#"
onClick={
{
"trackCourseEvent": {
"cardId": "cardId",
"eventName": [MockFunction segment.enterCourseClicked],
"upgradeUrl": "homeUrl",
},
}
}
>
View Course
</ActionButton>
`;
exports[`ViewCourseButton learner cannot view course 1`] = `
<ActionButton
as="a"
disabled={true}
href="#"
onClick={
{
"trackCourseEvent": {
"cardId": "cardId",
"eventName": [MockFunction segment.enterCourseClicked],
"upgradeUrl": "homeUrl",
},
}
}
>
View Course
</ActionButton>
`;

View File

@@ -1,6 +1,14 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import CourseCardActionSlot from 'plugin-slots/CourseCardActionSlot';
import UpgradeButton from './UpgradeButton';
import SelectSessionButton from './SelectSessionButton';
import BeginCourseButton from './BeginCourseButton';
import ResumeButton from './ResumeButton';
import ViewCourseButton from './ViewCourseButton';
import CourseCardActions from '.'; import CourseCardActions from '.';
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
@@ -12,15 +20,17 @@ jest.mock('hooks', () => ({
}, },
})); }));
jest.mock('plugin-slots/CourseCardActionSlot', () => jest.fn(() => <div>CourseCardActionSlot</div>)); jest.mock('plugin-slots/CourseCardActionSlot', () => 'CustomActionButton');
jest.mock('./SelectSessionButton', () => jest.fn(() => <div>SelectSessionButton</div>)); jest.mock('./UpgradeButton', () => 'UpgradeButton');
jest.mock('./ViewCourseButton', () => jest.fn(() => <div>ViewCourseButton</div>)); jest.mock('./SelectSessionButton', () => 'SelectSessionButton');
jest.mock('./BeginCourseButton', () => jest.fn(() => <div>BeginCourseButton</div>)); jest.mock('./ViewCourseButton', () => 'ViewCourseButton');
jest.mock('./ResumeButton', () => jest.fn(() => <div>ResumeButton</div>)); jest.mock('./BeginCourseButton', () => 'BeginCourseButton');
jest.mock('./ResumeButton', () => 'ResumeButton');
const cardId = 'test-card-id'; const cardId = 'test-card-id';
const props = { cardId }; const props = { cardId };
let el;
describe('CourseCardActions', () => { describe('CourseCardActions', () => {
const mockHooks = ({ const mockHooks = ({
isEntitlement = false, isEntitlement = false,
@@ -36,58 +46,71 @@ describe('CourseCardActions', () => {
reduxHooks.useCardEnrollmentData.mockReturnValueOnce({ isExecEd2UCourse, isVerified, hasStarted }); reduxHooks.useCardEnrollmentData.mockReturnValueOnce({ isExecEd2UCourse, isVerified, hasStarted });
reduxHooks.useMasqueradeData.mockReturnValueOnce({ isMasquerading }); reduxHooks.useMasqueradeData.mockReturnValueOnce({ isMasquerading });
}; };
const renderComponent = () => render(<CourseCardActions {...props} />); const render = () => {
describe('hooks', () => { el = shallow(<CourseCardActions {...props} />);
};
describe('behavior', () => {
it('initializes redux hooks', () => { it('initializes redux hooks', () => {
mockHooks(); mockHooks();
renderComponent(); render();
expect(reduxHooks.useCardEntitlementData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardEntitlementData).toHaveBeenCalledWith(cardId);
expect(reduxHooks.useCardEnrollmentData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardEnrollmentData).toHaveBeenCalledWith(cardId);
expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(cardId);
}); });
}); });
describe('output', () => { describe('output', () => {
describe('Exec Ed course', () => {
it('does not render upgrade button', () => {
mockHooks({ isExecEd2UCourse: true });
render();
expect(el.instance.findByType(UpgradeButton).length).toEqual(0);
});
});
describe('entitlement course', () => { describe('entitlement course', () => {
it('does not render upgrade button', () => {
mockHooks({ isEntitlement: true });
render();
expect(el.instance.findByType(UpgradeButton).length).toEqual(0);
});
it('renders ViewCourseButton if fulfilled', () => { it('renders ViewCourseButton if fulfilled', () => {
mockHooks({ isEntitlement: true, isFulfilled: true }); mockHooks({ isEntitlement: true, isFulfilled: true });
renderComponent(); render();
const ViewCourseButton = screen.getByText('ViewCourseButton'); expect(el.instance.findByType(ViewCourseButton)[0].props.cardId).toEqual(cardId);
expect(ViewCourseButton).toBeInTheDocument();
}); });
it('renders SelectSessionButton if not fulfilled', () => { it('renders SelectSessionButton if not fulfilled', () => {
mockHooks({ isEntitlement: true }); mockHooks({ isEntitlement: true });
renderComponent(); render();
const SelectSessionButton = screen.getByText('SelectSessionButton'); expect(el.instance.findByType(SelectSessionButton)[0].props.cardId).toEqual(cardId);
expect(SelectSessionButton).toBeInTheDocument(); });
});
describe('verified course', () => {
it('does not render upgrade button', () => {
mockHooks({ isVerified: true });
render();
expect(el.instance.findByType(UpgradeButton).length).toEqual(0);
}); });
}); });
describe('not entitlement, verified, or exec ed', () => { describe('not entitlement, verified, or exec ed', () => {
it('renders CourseCardActionSlot and ViewCourseButton for archived courses', () => { it('renders UpgradeButton and ViewCourseButton for archived courses', () => {
mockHooks({ isArchived: true }); mockHooks({ isArchived: true });
renderComponent(); render();
const CourseCardActionSlot = screen.getByText('CourseCardActionSlot'); expect(el.instance.findByType(CourseCardActionSlot)[0].props.cardId).toEqual(cardId);
expect(CourseCardActionSlot).toBeInTheDocument(); expect(el.instance.findByType(ViewCourseButton)[0].props.cardId).toEqual(cardId);
const ViewCourseButton = screen.getByText('ViewCourseButton');
expect(ViewCourseButton).toBeInTheDocument();
}); });
describe('unstarted courses', () => { describe('unstarted courses', () => {
it('renders CourseCardActionSlot and BeginCourseButton', () => { it('renders UpgradeButton and BeginCourseButton', () => {
mockHooks(); mockHooks();
renderComponent(); render();
const CourseCardActionSlot = screen.getByText('CourseCardActionSlot'); expect(el.instance.findByType(CourseCardActionSlot)[0].props.cardId).toEqual(cardId);
expect(CourseCardActionSlot).toBeInTheDocument(); expect(el.instance.findByType(BeginCourseButton)[0].props.cardId).toEqual(cardId);
const BeginCourseButton = screen.getByText('BeginCourseButton');
expect(BeginCourseButton).toBeInTheDocument();
}); });
}); });
describe('active courses (started, and not archived)', () => { describe('active courses (started, and not archived)', () => {
it('renders CourseCardActionSlot and ResumeButton', () => { it('renders UpgradeButton and ResumeButton', () => {
mockHooks({ hasStarted: true }); mockHooks({ hasStarted: true });
renderComponent(); render();
const CourseCardActionSlot = screen.getByText('CourseCardActionSlot'); expect(el.instance.findByType(CourseCardActionSlot)[0].props.cardId).toEqual(cardId);
expect(CourseCardActionSlot).toBeInTheDocument(); expect(el.instance.findByType(ResumeButton)[0].props.cardId).toEqual(cardId);
const ResumeButton = screen.getByText('ResumeButton');
expect(ResumeButton).toBeInTheDocument();
}); });
}); });
}); });

View File

@@ -1,6 +1,11 @@
import { defineMessages } from '@edx/frontend-platform/i18n'; import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({ const messages = defineMessages({
upgrade: {
id: 'learner-dash.courseCard.actions.upgrade',
description: 'Course card upgrade button text',
defaultMessage: 'Upgrade',
},
beginCourse: { beginCourse: {
id: 'learner-dash.courseCard.actions.beginCourse', id: 'learner-dash.courseCard.actions.beginCourse',
description: 'Course card begin-course button text', description: 'Course card begin-course button text',

View File

@@ -1,8 +1,8 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import CertificateBanner from './CertificateBanner'; import CertificateBanner from './CertificateBanner';
import messages from './messages';
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
utilHooks: { utilHooks: {
@@ -17,28 +17,28 @@ jest.mock('hooks', () => ({
}, },
})); }));
const defaultCertificate = { jest.mock('components/Banner', () => 'Banner');
availableDate: '10/20/3030',
isRestricted: false,
isDownloadable: false,
isEarnedButUnavailable: false,
};
const defaultEnrollment = {
isAudit: false,
isVerified: false,
};
const defaultCourseRun = { isArchived: false };
const defaultGrade = { isPassing: false };
const defaultPlatformSettings = {};
const props = { cardId: 'cardId' };
const supportEmail = 'suport@email.com';
const billingEmail = 'billing@email.com';
describe('CertificateBanner', () => { describe('CertificateBanner', () => {
const props = { cardId: 'cardId' };
reduxHooks.useCardCourseRunData.mockReturnValue({ reduxHooks.useCardCourseRunData.mockReturnValue({
minPassingGrade: 0.8, minPassingGrade: 0.8,
progressUrl: 'progressUrl', progressUrl: 'progressUrl',
}); });
const defaultCertificate = {
availableDate: '10/20/3030',
isRestricted: false,
isDownloadable: false,
isEarnedButUnavailable: false,
};
const defaultEnrollment = {
isAudit: false,
isVerified: false,
};
const defaultCourseRun = { isArchived: false };
const defaultGrade = { isPassing: false };
const defaultPlatformSettings = {};
const createWrapper = ({ const createWrapper = ({
certificate = {}, certificate = {},
enrollment = {}, enrollment = {},
@@ -51,192 +51,177 @@ describe('CertificateBanner', () => {
reduxHooks.useCardEnrollmentData.mockReturnValueOnce({ ...defaultEnrollment, ...enrollment }); reduxHooks.useCardEnrollmentData.mockReturnValueOnce({ ...defaultEnrollment, ...enrollment });
reduxHooks.useCardCourseRunData.mockReturnValueOnce({ ...defaultCourseRun, ...courseRun }); reduxHooks.useCardCourseRunData.mockReturnValueOnce({ ...defaultCourseRun, ...courseRun });
reduxHooks.usePlatformSettingsData.mockReturnValueOnce({ ...defaultPlatformSettings, ...platformSettings }); reduxHooks.usePlatformSettingsData.mockReturnValueOnce({ ...defaultPlatformSettings, ...platformSettings });
return render(<IntlProvider locale="en"><CertificateBanner {...props} /></IntlProvider>); return shallow(<CertificateBanner {...props} />);
}; };
beforeEach(() => { /** TODO: Update tests to validate snapshots **/
jest.clearAllMocks(); describe('snapshot', () => {
}); test('is restricted', () => {
it('is restricted', () => { const wrapper = createWrapper({
createWrapper({ certificate: {
certificate: { isRestricted: true,
isRestricted: true, },
}, });
expect(wrapper.snapshot).toMatchSnapshot();
}); });
const banner = screen.getByRole('alert'); test('is restricted with support email', () => {
expect(banner).toBeInTheDocument(); const wrapper = createWrapper({
const msg = screen.getByText((text) => text.includes('please let us know.')); certificate: {
expect(msg).toBeInTheDocument(); isRestricted: true,
expect(msg).not.toContain(supportEmail); },
}); platformSettings: {
it('is restricted with support email', () => { supportEmail: 'suport@email',
createWrapper({ },
certificate: { });
isRestricted: true, expect(wrapper.snapshot).toMatchSnapshot();
},
platformSettings: {
supportEmail,
},
}); });
const banner = screen.getByRole('alert'); test('is restricted with billing email', () => {
expect(banner).toBeInTheDocument(); const wrapper = createWrapper({
const msg = screen.getByText((text) => text.includes(supportEmail)); certificate: {
expect(msg).toBeInTheDocument(); isRestricted: true,
}); },
it('is restricted with billing email but not verified', () => { platformSettings: {
createWrapper({ billingEmail: 'billing@email',
certificate: { },
isRestricted: true, });
}, expect(wrapper.snapshot).toMatchSnapshot();
platformSettings: {
billingEmail,
},
}); });
const banner = screen.getByRole('alert'); test('is restricted and verified', () => {
expect(banner).toBeInTheDocument(); const wrapper = createWrapper({
expect(banner).toHaveClass('alert-danger'); certificate: {
const msg = screen.queryByText((text) => text.includes(billingEmail)); isRestricted: true,
expect(msg).not.toBeInTheDocument(); },
}); enrollment: {
it('is restricted and verified', () => { isVerified: true,
createWrapper({ },
certificate: { });
isRestricted: true, expect(wrapper.snapshot).toMatchSnapshot();
},
enrollment: {
isVerified: true,
},
}); });
const banner = screen.getByRole('alert'); test('is restricted and verified with support email', () => {
expect(banner).toBeInTheDocument(); const wrapper = createWrapper({
const restrictedMsg = screen.getByText((text) => text.includes('please let us know.')); certificate: {
expect(restrictedMsg).toBeInTheDocument(); isRestricted: true,
const refundMsg = screen.getByText((text) => text.includes('If you would like a refund')); },
expect(refundMsg).toBeInTheDocument(); enrollment: {
}); isVerified: true,
it('is restricted and verified with support email', () => { },
createWrapper({ platformSettings: {
certificate: { supportEmail: 'suport@email',
isRestricted: true, },
}, });
enrollment: { expect(wrapper.snapshot).toMatchSnapshot();
isVerified: true,
},
platformSettings: {
supportEmail,
},
}); });
const restrictedMsg = screen.getByText((text) => text.includes(supportEmail)); test('is restricted and verified with billing email', () => {
expect(restrictedMsg).toBeInTheDocument(); const wrapper = createWrapper({
const refundMsg = screen.getByText((text) => text.includes('If you would like a refund')); certificate: {
expect(refundMsg).toBeInTheDocument(); isRestricted: true,
expect(refundMsg.innerHTML).not.toContain(billingEmail); },
}); enrollment: {
it('is restricted and verified with billing email', () => { isVerified: true,
createWrapper({ },
certificate: { platformSettings: {
isRestricted: true, billingEmail: 'billing@email',
}, },
enrollment: { });
isVerified: true, expect(wrapper.snapshot).toMatchSnapshot();
},
platformSettings: {
billingEmail,
},
}); });
const restrictedMsg = screen.queryByText((text) => text.includes('please let us know.')); test('is restricted and verified with support and billing email', () => {
expect(restrictedMsg).toBeInTheDocument(); const wrapper = createWrapper({
expect(restrictedMsg.innerHTML).not.toContain(supportEmail); certificate: {
const refundMsg = screen.getByText((text) => text.includes(billingEmail)); isRestricted: true,
expect(refundMsg).toBeInTheDocument(); },
}); enrollment: {
it('is restricted and verified with support and billing email', () => { isVerified: true,
createWrapper({ },
certificate: { platformSettings: {
isRestricted: true, supportEmail: 'suport@email',
}, billingEmail: 'billing@email',
enrollment: { },
isVerified: true, });
}, expect(wrapper.snapshot).toMatchSnapshot();
platformSettings: {
supportEmail,
billingEmail,
},
}); });
const restrictedMsg = screen.getByText((text) => text.includes(supportEmail)); test('is passing and is downloadable', () => {
expect(restrictedMsg).toBeInTheDocument(); const wrapper = createWrapper({
const refundMsg = screen.getByText((text) => text.includes(billingEmail)); grade: { isPassing: true },
expect(refundMsg).toBeInTheDocument(); certificate: { isDownloadable: true },
}); });
it('is passing and is downloadable', () => { expect(wrapper.snapshot).toMatchSnapshot();
createWrapper({
grade: { isPassing: true },
certificate: { isDownloadable: true },
}); });
const banner = screen.getByRole('alert'); test('not passing and is downloadable', () => {
expect(banner).toBeInTheDocument(); const wrapper = createWrapper({
expect(banner).toHaveClass('alert-success'); grade: { isPassing: false },
const readyMsg = screen.getByText((text) => text.includes('Congratulations.')); certificate: { isDownloadable: true },
expect(readyMsg).toBeInTheDocument(); });
}); expect(wrapper.snapshot).toMatchSnapshot();
it('not passing and is downloadable', () => {
createWrapper({
grade: { isPassing: false },
certificate: { isDownloadable: true },
}); });
const banner = screen.getByRole('alert'); test('not passing and audit', () => {
expect(banner).toBeInTheDocument(); const wrapper = createWrapper({
expect(banner).toHaveClass('alert-success'); enrollment: {
const readyMsg = screen.getByText((text) => text.includes('Congratulations.')); isAudit: true,
expect(readyMsg).toBeInTheDocument(); },
}); });
it('not passing and audit', () => { expect(wrapper.snapshot).toMatchSnapshot();
createWrapper({
enrollment: {
isAudit: true,
},
}); });
const banner = screen.getByRole('alert'); test('not passing and has finished', () => {
expect(banner).toHaveClass('alert-info'); const wrapper = createWrapper({
const auditMsg = screen.getByText((text) => text.includes('Grade required to pass the course:')); courseRun: { isArchived: true },
expect(auditMsg).toBeInTheDocument(); });
}); expect(wrapper.snapshot).toMatchSnapshot();
it('not passing and has finished', () => {
createWrapper({
courseRun: { isArchived: true },
}); });
const banner = screen.getByRole('alert'); test('not passing and not audit and not finished', () => {
expect(banner).toHaveClass('alert-warning'); const wrapper = createWrapper({});
const archivedMsg = screen.getByText('You are not eligible for a certificate.'); expect(wrapper.snapshot).toMatchSnapshot();
expect(archivedMsg).toBeInTheDocument();
});
it('not passing and not audit and not finished', () => {
createWrapper({});
const banner = screen.getByRole('alert');
expect(banner).toHaveClass('alert-warning');
const msg = screen.getByText((text) => text.includes('Grade required for a certificate'));
expect(msg).toBeInTheDocument();
});
it('is passing and is earned but unavailable', () => {
createWrapper({
grade: {
isPassing: true,
},
certificate: {
isEarnedButUnavailable: true,
},
}); });
const banner = screen.getByRole('alert'); test('is passing and is earned but unavailable', () => {
expect(banner).toHaveClass('alert-info'); const wrapper = createWrapper({
const earnedMsg = screen.getByText((text) => text.includes('Your grade and certificate will be ready after')); grade: {
expect(earnedMsg).toBeInTheDocument(); isPassing: true,
}); },
it('is passing and not downloadable render empty', () => { certificate: {
createWrapper({ isEarnedButUnavailable: true,
grade: { },
isPassing: true, });
}, expect(wrapper.snapshot).toMatchSnapshot();
});
test('is passing and not downloadable render empty', () => {
const wrapper = createWrapper({
grade: {
isPassing: true,
},
});
expect(wrapper.snapshot).toMatchSnapshot();
});
});
describe('behavior', () => {
it('is restricted', () => {
const wrapper = createWrapper({
certificate: {
isRestricted: true,
},
platformSettings: {
supportEmail: 'suport@email',
billingEmail: 'billing@email',
},
});
const bannerMessage = wrapper.instance.findByType('format-message-function').map(el => el.props.message.defaultMessage).join('\n');
expect(bannerMessage).toEqual(messages.certRestricted.defaultMessage);
expect(bannerMessage).toContain(messages.certRestricted.defaultMessage);
});
it('is restricted and verified', () => {
const wrapper = createWrapper({
certificate: {
isRestricted: true,
},
enrollment: {
isVerified: true,
},
platformSettings: {
supportEmail: 'suport@email',
billingEmail: 'billing@email',
},
});
const bannerMessage = wrapper.instance.findByType('format-message-function').map(el => el.props.message.defaultMessage).join('\n');
expect(bannerMessage).toContain(messages.certRestricted.defaultMessage);
expect(bannerMessage).toContain(messages.certRefundContactBilling.defaultMessage);
}); });
const banner = screen.queryByRole('alert');
expect(banner).toBeNull();
}); });
}); });

View File

@@ -12,6 +12,7 @@ export const CourseBanner = ({ cardId }) => {
const { const {
isVerified, isVerified,
isAuditAccessExpired, isAuditAccessExpired,
canUpgrade,
coursewareAccess = {}, coursewareAccess = {},
} = reduxHooks.useCardEnrollmentData(cardId); } = reduxHooks.useCardEnrollmentData(cardId);
const courseRun = reduxHooks.useCardCourseRunData(cardId); const courseRun = reduxHooks.useCardCourseRunData(cardId);
@@ -25,7 +26,13 @@ export const CourseBanner = ({ cardId }) => {
return ( return (
<> <>
{isAuditAccessExpired {isAuditAccessExpired
&& ( && (canUpgrade ? (
<Banner>
{formatMessage(messages.auditAccessExpired)}
{' '}
{formatMessage(messages.upgradeToAccess)}
</Banner>
) : (
<Banner> <Banner>
{formatMessage(messages.auditAccessExpired)} {formatMessage(messages.auditAccessExpired)}
{' '} {' '}
@@ -33,7 +40,17 @@ export const CourseBanner = ({ cardId }) => {
{formatMessage(messages.findAnotherCourse)} {formatMessage(messages.findAnotherCourse)}
</Hyperlink> </Hyperlink>
</Banner> </Banner>
)} ))}
{courseRun.isActive && !canUpgrade && (
<Banner>
{formatMessage(messages.upgradeDeadlinePassed)}
{' '}
<Hyperlink isInline destination={courseRun.marketingUrl || ''}>
{formatMessage(messages.exploreCourseDetails)}
</Hyperlink>
</Banner>
)}
{(!isStaff && isTooEarly && courseRun.startDate) && ( {(!isStaff && isTooEarly && courseRun.startDate) && (
<Banner> <Banner>
@@ -42,7 +59,6 @@ export const CourseBanner = ({ cardId }) => {
})} })}
</Banner> </Banner>
)} )}
{(!isStaff && hasUnmetPrerequisites) && ( {(!isStaff && hasUnmetPrerequisites) && (
<Banner>{formatMessage(messages.prerequisitesNotMet)}</Banner> <Banner>{formatMessage(messages.prerequisitesNotMet)}</Banner>
)} )}

View File

@@ -1,5 +1,6 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import { IntlProvider } from '@edx/frontend-platform/i18n'; import { shallow } from '@edx/react-unit-test-utils';
import { Hyperlink } from '@openedx/paragon';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import { formatMessage } from 'testUtils'; import { formatMessage } from 'testUtils';
@@ -7,6 +8,7 @@ import { CourseBanner } from './CourseBanner';
import messages from './messages'; import messages from './messages';
jest.mock('components/Banner', () => 'Banner');
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
utilHooks: { utilHooks: {
useFormatDate: () => date => date, useFormatDate: () => date => date,
@@ -17,10 +19,13 @@ jest.mock('hooks', () => ({
}, },
})); }));
const cardId = 'test-card-id'; const cardId = 'my-test-course-number';
let el;
const enrollmentData = { const enrollmentData = {
isVerified: false, isVerified: false,
canUpgrade: false,
isAuditAccessExpired: false, isAuditAccessExpired: false,
coursewareAccess: { coursewareAccess: {
hasUnmetPrerequisites: false, hasUnmetPrerequisites: false,
@@ -34,7 +39,7 @@ const courseRunData = {
marketingUrl: 'marketing-url', marketingUrl: 'marketing-url',
}; };
const renderCourseBanner = (overrides = {}) => { const render = (overrides = {}) => {
const { const {
courseRun = {}, courseRun = {},
enrollment = {}, enrollment = {},
@@ -47,58 +52,114 @@ const renderCourseBanner = (overrides = {}) => {
...enrollmentData, ...enrollmentData,
...enrollment, ...enrollment,
}); });
return render(<IntlProvider locale="en"><CourseBanner cardId={cardId} /></IntlProvider>); el = shallow(<CourseBanner cardId={cardId} />);
}; };
describe('CourseBanner', () => { describe('CourseBanner', () => {
it('initializes data with course number from enrollment, course and course run data', () => { test('initializes data with course number from enrollment, course and course run data', () => {
renderCourseBanner(); render();
expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(cardId);
expect(reduxHooks.useCardEnrollmentData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardEnrollmentData).toHaveBeenCalledWith(cardId);
}); });
it('no display if learner is verified', () => { test('no display if learner is verified', () => {
renderCourseBanner({ enrollment: { isVerified: true } }); render({ enrollment: { isVerified: true } });
expect(screen.queryByRole('alert')).toBeNull(); expect(el.isEmptyRender()).toEqual(true);
}); });
describe('audit access expired', () => { describe('audit access expired, can upgrade', () => {
it('should display correct message and link', () => { beforeEach(() => {
renderCourseBanner({ enrollment: { isAuditAccessExpired: true } }); render({ enrollment: { isAuditAccessExpired: true, canUpgrade: true } });
const auditAccessText = screen.getByText(formatMessage(messages.auditAccessExpired)); });
expect(auditAccessText).toBeInTheDocument(); test('snapshot: (auditAccessExpired, upgradeToAccess)', () => {
const auditAccessLink = screen.getByText(formatMessage(messages.findAnotherCourse)); expect(el.snapshot).toMatchSnapshot();
expect(auditAccessLink).toBeInTheDocument(); });
test('messages: (auditAccessExpired, upgradeToAccess)', () => {
expect(el.instance.children[0].children[0].el).toContain(messages.auditAccessExpired.defaultMessage);
expect(el.instance.children[0].children[2].el).toContain(messages.upgradeToAccess.defaultMessage);
}); });
}); });
describe('audit access expired, cannot upgrade', () => {
beforeEach(() => {
render({ enrollment: { isAuditAccessExpired: true } });
});
test('snapshot: (auditAccessExpired, findAnotherCourse hyperlink)', () => {
expect(el.snapshot).toMatchSnapshot();
});
test('messages: (auditAccessExpired, upgradeToAccess)', () => {
expect(el.instance.children[0].children[0].el).toContain(messages.auditAccessExpired.defaultMessage);
expect(el.instance.findByType(Hyperlink)[0].children[0].el).toEqual(messages.findAnotherCourse.defaultMessage);
});
});
describe('course run active and cannot upgrade', () => {
beforeEach(() => {
render({ courseRun: { isActive: true } });
});
test('snapshot: (upgradseDeadlinePassed, exploreCourseDetails hyperlink)', () => {
expect(el.snapshot).toMatchSnapshot();
});
test('messages: (upgradseDeadlinePassed, exploreCourseDetails hyperlink)', () => {
expect(el.instance.children[0].children[0].el).toContain(messages.upgradeDeadlinePassed.defaultMessage);
const link = el.instance.findByType(Hyperlink);
expect(link[0].children[0].el).toEqual(messages.exploreCourseDetails.defaultMessage);
expect(link[0].props.destination).toEqual(courseRunData.marketingUrl);
});
});
test('no display if audit access not expired and (course is not active or can upgrade)', () => {
render();
// isEmptyRender() isn't true because the minimal is <Fragment />
expect(el.instance.children).toEqual([]);
render({ enrollment: { canUpgrade: true }, courseRun: { isActive: true } });
expect(el.instance.children).toEqual([]);
});
describe('unmet prerequisites', () => { describe('unmet prerequisites', () => {
it('should display correct message', () => { beforeEach(() => {
renderCourseBanner({ enrollment: { coursewareAccess: { hasUnmetPrerequisites: true } } }); render({ enrollment: { coursewareAccess: { hasUnmetPrerequisites: true } } });
const preReqText = screen.getByText(formatMessage(messages.prerequisitesNotMet)); });
expect(preReqText).toBeInTheDocument(); test('snapshot: unmetPrerequisites', () => {
expect(el.snapshot).toMatchSnapshot();
});
test('messages: prerequisitesNotMet', () => {
expect(el.instance.children[0].children[0].el).toContain(messages.prerequisitesNotMet.defaultMessage);
}); });
}); });
describe('too early', () => { describe('too early', () => {
describe('no start date', () => { describe('no start date', () => {
it('should not display banner', () => { beforeEach(() => {
renderCourseBanner({ enrollment: { coursewareAccess: { isTooEarly: true } }, courseRun: { startDate: null } }); render({ enrollment: { coursewareAccess: { isTooEarly: true } }, courseRun: { startDate: null } });
const banner = screen.queryByRole('alert');
expect(banner).toBeNull();
}); });
test('snapshot', () => expect(el.snapshot).toMatchSnapshot());
test('messages', () => expect(el.instance.children).toEqual([]));
}); });
describe('has start date', () => { describe('has start date', () => {
it('should display messages courseHasNotStarted', () => { beforeEach(() => {
renderCourseBanner({ enrollment: { coursewareAccess: { isTooEarly: true } } }); render({ enrollment: { coursewareAccess: { isTooEarly: true } } });
const earlyMsg = screen.getByText( });
test('snapshot', () => expect(el.snapshot).toMatchSnapshot());
test('messages: courseHasNotStarted', () => {
expect(el.instance.children[0].children[0].el).toContain(
formatMessage(messages.courseHasNotStarted, { startDate: courseRunData.startDate }), formatMessage(messages.courseHasNotStarted, { startDate: courseRunData.startDate }),
); );
expect(earlyMsg).toBeInTheDocument();
}); });
}); });
}); });
describe('staff', () => { describe('staff', () => {
it('should not display banner', () => { beforeEach(() => {
renderCourseBanner({ enrollment: { coursewareAccess: { isStaff: true } } }); render({ enrollment: { coursewareAccess: { isStaff: true } } });
const banner = screen.queryByRole('alert'); });
expect(banner).toBeNull(); test('snapshot: isStaff', () => {
expect(el.snapshot).toMatchSnapshot();
}); });
}); });
test('snapshot: stacking banners', () => {
render({
enrollment: {
coursewareAccess: {
isStaff: true,
isTooEarly: true,
hasUnmetPrerequisites: true,
},
},
});
expect(el.snapshot).toMatchSnapshot();
});
}); });

View File

@@ -0,0 +1,58 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`CreditBanner component render with error state snapshot 1`] = `
<Banner
variant="danger"
>
<p
className="credit-error-msg"
data-testid="credit-error-msg"
>
<format-message-function
message={
{
"defaultMessage": "An error occurred with this transaction. For help, contact {supportEmailLink}.",
"description": "",
"id": "learner-dash.courseCard.banners.credit.error",
}
}
values={
{
"supportEmailLink": <MailtoLink
to="test-support-email"
>
test-support-email
</MailtoLink>,
}
}
/>
</p>
<ContentComponent
cardId="test-card-id"
/>
</Banner>
`;
exports[`CreditBanner component render with error state with no email snapshot 1`] = `
<Banner
variant="danger"
>
<p
className="credit-error-msg"
data-testid="credit-error-msg"
>
An error occurred with this transaction.
</p>
<ContentComponent
cardId="test-card-id"
/>
</Banner>
`;
exports[`CreditBanner component render with no error state snapshot 1`] = `
<Banner>
<ContentComponent
cardId="test-card-id"
/>
</Banner>
`;

View File

@@ -1,65 +1,95 @@
import { screen, render } from '@testing-library/react'; import React from 'react';
import { IntlProvider } from '@edx/frontend-platform/i18n'; import { shallow } from '@edx/react-unit-test-utils';
import { formatMessage } from 'testUtils';
import { MailtoLink } from '@openedx/paragon';
import hooks from './hooks'; import hooks from './hooks';
import { CreditBanner } from '.'; import messages from './messages';
import CreditBanner from '.';
jest.mock('components/Banner', () => 'Banner');
jest.mock('./hooks', () => ({ jest.mock('./hooks', () => ({
useCreditBannerData: jest.fn(), useCreditBannerData: jest.fn(),
})); }));
describe('CreditBanner', () => { let el;
const mockCardId = 'test-card-id'; const cardId = 'test-card-id';
const mockContentComponent = () => <div data-testid="mock-content">Test Content</div>;
const mockSupportEmail = 'support@test.com';
const renderCreditBanner = () => render( const ContentComponent = () => 'ContentComponent';
<IntlProvider locale="en"> const supportEmail = 'test-support-email';
<CreditBanner cardId={mockCardId} />
</IntlProvider>,
);
beforeEach(() => { describe('CreditBanner component', () => {
jest.clearAllMocks(); describe('behavior', () => {
}); beforeEach(() => {
hooks.useCreditBannerData.mockReturnValue(null);
it('should return null if hook returns null', () => { el = shallow(<CreditBanner cardId={cardId} />);
hooks.useCreditBannerData.mockReturnValue(null);
renderCreditBanner();
const banner = screen.queryByRole('alert');
expect(banner).toBeNull();
});
it('should render content component without error', () => {
hooks.useCreditBannerData.mockReturnValue({
ContentComponent: mockContentComponent,
error: false,
}); });
renderCreditBanner(); it('initializes hooks with cardId', () => {
expect(hooks.useCreditBannerData).toHaveBeenCalledWith(cardId);
expect(screen.getByTestId('mock-content')).toBeInTheDocument();
expect(screen.queryByTestId('credit-error-msg')).not.toBeInTheDocument();
});
it('should render error message with support email', () => {
hooks.useCreditBannerData.mockReturnValue({
ContentComponent: mockContentComponent,
error: true,
supportEmail: mockSupportEmail,
}); });
renderCreditBanner(); it('returns null if hookData is null', () => {
expect(el.isEmptyRender()).toEqual(true);
expect(screen.getByTestId('credit-error-msg')).toBeInTheDocument(); });
expect(screen.getByText(mockSupportEmail)).toBeInTheDocument(); });
}); describe('render', () => {
describe('with error state', () => {
it('should render error message without support email', () => { beforeEach(() => {
hooks.useCreditBannerData.mockReturnValue({ hooks.useCreditBannerData.mockReturnValue({
ContentComponent: mockContentComponent, error: true,
error: true, ContentComponent,
supportEmail,
});
el = shallow(<CreditBanner cardId={cardId} />);
});
test('snapshot', () => {
expect(el.snapshot).toMatchSnapshot();
});
it('passes danger variant to Banner parent', () => {
expect(el.instance.findByType('Banner')[0].props.variant).toEqual('danger');
});
it('includes credit-error-msg with support email link', () => {
expect(el.instance.findByTestId('credit-error-msg')[0].children[0].el).toEqual(shallow(formatMessage(messages.error, {
supportEmailLink: (<MailtoLink to={supportEmail}>{supportEmail}</MailtoLink>),
})));
});
it('loads ContentComponent with cardId', () => {
expect(el.instance.findByType('ContentComponent')[0].props.cardId).toEqual(cardId);
});
}); });
renderCreditBanner();
expect(screen.getByTestId('credit-error-msg')).toBeInTheDocument(); describe('with error state with no email', () => {
expect(screen.queryByText(mockSupportEmail)).not.toBeInTheDocument(); beforeEach(() => {
hooks.useCreditBannerData.mockReturnValue({
error: true,
ContentComponent,
});
el = shallow(<CreditBanner cardId={cardId} />);
});
test('snapshot', () => {
expect(el.snapshot).toMatchSnapshot();
});
it('includes credit-error-msg without support email link', () => {
expect(el.instance.findByTestId('credit-error-msg')[0].children[0].el).toEqual(formatMessage(messages.errorNoEmail));
});
});
describe('with no error state', () => {
beforeEach(() => {
hooks.useCreditBannerData.mockReturnValue({
error: false,
ContentComponent,
supportEmail,
});
el = shallow(<CreditBanner cardId={cardId} />);
});
test('snapshot', () => {
expect(el.snapshot).toMatchSnapshot();
});
it('loads ContentComponent with cardId', () => {
expect(el.instance.findByType('ContentComponent')[0].props.cardId).toEqual(cardId);
});
});
}); });
}); });

View File

@@ -1,8 +1,10 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import { IntlProvider } from '@edx/frontend-platform/i18n'; import { shallow } from '@edx/react-unit-test-utils';
import { formatMessage } from 'testUtils'; import { formatMessage } from 'testUtils';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import messages from './messages'; import messages from './messages';
import ProviderLink from './components/ProviderLink';
import ApprovedContent from './ApprovedContent'; import ApprovedContent from './ApprovedContent';
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
@@ -11,7 +13,10 @@ jest.mock('hooks', () => ({
useMasqueradeData: jest.fn(), useMasqueradeData: jest.fn(),
}, },
})); }));
jest.mock('./components/CreditContent', () => 'CreditContent');
jest.mock('./components/ProviderLink', () => 'ProviderLink');
let el;
const cardId = 'test-card-id'; const cardId = 'test-card-id';
const credit = { const credit = {
providerStatusUrl: 'test-credit-provider-status-url', providerStatusUrl: 'test-credit-provider-status-url',
@@ -21,54 +26,38 @@ reduxHooks.useCardCreditData.mockReturnValue(credit);
reduxHooks.useMasqueradeData.mockReturnValue({ isMasquerading: false }); reduxHooks.useMasqueradeData.mockReturnValue({ isMasquerading: false });
describe('ApprovedContent component', () => { describe('ApprovedContent component', () => {
describe('hooks', () => { beforeEach(() => {
el = shallow(<ApprovedContent cardId={cardId} />);
});
describe('behavior', () => {
it('initializes credit data with cardId', () => { it('initializes credit data with cardId', () => {
render(<IntlProvider locale="en"><ApprovedContent cardId={cardId} /></IntlProvider>);
expect(reduxHooks.useCardCreditData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardCreditData).toHaveBeenCalledWith(cardId);
}); });
}); });
describe('render', () => { describe('render', () => {
describe('rendered CreditContent component', () => { describe('rendered CreditContent component', () => {
beforeEach(() => { let component;
jest.clearAllMocks(); beforeAll(() => {
render(<IntlProvider locale="en"><ApprovedContent cardId={cardId} /></IntlProvider>); component = el.instance.findByType('CreditContent');
}); });
it('action.message is formatted viewCredit message', () => { test('action.href from credit.providerStatusUrl', () => {
const actionButton = screen.getByRole('link', { name: messages.viewCredit.defaultMessage }); expect(component[0].props.action.href).toEqual(credit.providerStatusUrl);
expect(actionButton).toBeInTheDocument();
expect(actionButton).toHaveTextContent(formatMessage(messages.viewCredit));
}); });
it('action.href from credit.providerStatusUrl', () => { test('action.message is formatted viewCredit message', () => {
const actionButton = screen.getByRole('link', { name: messages.viewCredit.defaultMessage }); expect(component[0].props.action.message).toEqual(formatMessage(messages.viewCredit));
expect(actionButton).toHaveAttribute('href', credit.providerStatusUrl);
}); });
it('action.disabled is false', () => { test('action.disabled is false', () => {
const actionButton = screen.getByRole('link', { name: messages.viewCredit.defaultMessage }); expect(component[0].props.action.disabled).toEqual(false);
expect(actionButton).not.toHaveAttribute('aria-disabled', 'true');
expect(actionButton).not.toHaveClass('disabled');
expect(actionButton).toBeEnabled();
}); });
it('message is formatted approved message', () => { test('message is formatted approved message', () => {
const creditMsg = screen.getByTestId('credit-msg'); expect(component[0].props.message).toEqual(formatMessage(
expect(creditMsg).toBeInTheDocument(); messages.approved,
expect(creditMsg.textContent).toContain(`${credit.providerName} has approved your request for course credit`); {
}); congratulations: (<b>{formatMessage(messages.congratulations)}</b>),
}); linkToProviderSite: <ProviderLink cardId={cardId} />,
describe('when masquerading', () => { providerName: credit.providerName,
beforeEach(() => { },
reduxHooks.useMasqueradeData.mockReturnValue({ isMasquerading: true }); ));
render(<IntlProvider locale="en"><ApprovedContent cardId={cardId} /></IntlProvider>);
});
it('disables the action button', () => {
const actionButton = screen.getByRole('link', { name: messages.viewCredit.defaultMessage });
expect(actionButton).toHaveAttribute('aria-disabled', 'true');
expect(actionButton).toHaveClass('disabled');
});
it('still renders provider name and link correctly', () => {
const creditMsg = screen.getByTestId('credit-msg');
expect(creditMsg.textContent).toContain(credit.providerName);
}); });
}); });
}); });

View File

@@ -1,8 +1,8 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import userEvent from '@testing-library/user-event'; import { shallow } from '@edx/react-unit-test-utils';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import { formatMessage } from 'testUtils';
import track from 'tracking'; import track from 'tracking';
import messages from './messages'; import messages from './messages';
@@ -14,13 +14,16 @@ jest.mock('hooks', () => ({
useCardCourseRunData: jest.fn(), useCardCourseRunData: jest.fn(),
}, },
})); }));
jest.mock('./components/CreditContent', () => 'CreditContent');
jest.mock('tracking', () => ({ jest.mock('tracking', () => ({
credit: { credit: {
purchase: jest.fn(), purchase: (...args) => ({ trackCredit: args }),
}, },
})); }));
let el;
let component;
const cardId = 'test-card-id'; const cardId = 'test-card-id';
const courseId = 'test-course-id'; const courseId = 'test-course-id';
const credit = { const credit = {
@@ -29,45 +32,50 @@ const credit = {
reduxHooks.useCardCreditData.mockReturnValue(credit); reduxHooks.useCardCreditData.mockReturnValue(credit);
reduxHooks.useCardCourseRunData.mockReturnValue({ courseId }); reduxHooks.useCardCourseRunData.mockReturnValue({ courseId });
const renderEligibleContent = () => render(<IntlProvider locale="en" messages={{}}><EligibleContent cardId={cardId} /></IntlProvider>); const render = () => {
el = shallow(<EligibleContent cardId={cardId} />);
};
const loadComponent = () => {
component = el.instance.findByType('CreditContent');
};
describe('EligibleContent component', () => { describe('EligibleContent component', () => {
describe('hooks', () => { beforeEach(() => {
render();
});
describe('behavior', () => {
it('initializes credit data with cardId', () => { it('initializes credit data with cardId', () => {
renderEligibleContent();
expect(reduxHooks.useCardCreditData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardCreditData).toHaveBeenCalledWith(cardId);
}); });
it('initializes course run data with cardId', () => { it('initializes course run data with cardId', () => {
renderEligibleContent();
expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(cardId);
}); });
}); });
describe('behavior', () => { describe('render', () => {
describe('rendered CreditContent component', () => { describe('rendered CreditContent component', () => {
it('action message is formatted getCredit message', () => { beforeEach(() => {
renderEligibleContent(); loadComponent();
const button = screen.getByRole('button', { name: messages.getCredit.defaultMessage });
expect(button).toBeInTheDocument();
}); });
it('onClick sends credit purchase track event', async () => { test('action.onClick sends credit purchase track event', () => {
const user = userEvent.setup(); expect(component[0].props.action.onClick).toEqual(
renderEligibleContent(); track.credit.purchase(courseId),
const button = screen.getByRole('button', { name: messages.getCredit.defaultMessage }); );
await user.click(button);
expect(track.credit.purchase).toHaveBeenCalledWith(courseId);
}); });
it('message is formatted eligible message if provider', () => { test('action.message is formatted getCredit message', () => {
renderEligibleContent(); expect(component[0].props.action.message).toEqual(formatMessage(messages.getCredit));
const eligibleMessage = screen.getByTestId('credit-msg');
expect(eligibleMessage).toBeInTheDocument();
expect(eligibleMessage).toHaveTextContent(credit.providerName);
}); });
it('message is formatted eligible message if no provider', () => { test('message is formatted eligible message if no provider', () => {
reduxHooks.useCardCreditData.mockReturnValue({}); reduxHooks.useCardCreditData.mockReturnValueOnce({});
renderEligibleContent(); render();
const eligibleMessage = screen.getByTestId('credit-msg'); loadComponent();
expect(eligibleMessage).toBeInTheDocument(); expect(component[0].props.message).toEqual(formatMessage(
expect(eligibleMessage).toHaveTextContent(messages.getCredit.defaultMessage); messages.eligible,
{ getCredit: (<b>{formatMessage(messages.getCredit)}</b>) },
));
});
test('message is formatted eligible message if provider', () => {
expect(component[0].props.message).toEqual(
formatMessage(messages.eligibleFromProvider, { providerName: credit.providerName }),
);
}); });
}); });
}); });

View File

@@ -1,103 +1,73 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import { IntlProvider } from '@edx/frontend-platform/i18n'; import { shallow } from '@edx/react-unit-test-utils';
import userEvent from '@testing-library/user-event';
import { formatMessage } from 'testUtils';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import messages from './messages'; import messages from './messages';
import hooks from './hooks'; import hooks from './hooks';
import ProviderLink from './components/ProviderLink';
import MustRequestContent from './MustRequestContent'; import MustRequestContent from './MustRequestContent';
jest.mock('./hooks', () => ({ jest.mock('./hooks', () => ({
useCreditRequestData: jest.fn(), useCreditRequestData: jest.fn(),
})); }));
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
reduxHooks: { reduxHooks: { useMasqueradeData: jest.fn() },
useMasqueradeData: jest.fn(),
useCardCreditData: jest.fn(),
},
})); }));
jest.mock('./components/CreditContent', () => 'CreditContent');
jest.mock('./components/ProviderLink', () => 'ProviderLink');
let el;
let component;
const cardId = 'test-card-id'; const cardId = 'test-card-id';
const requestData = { const requestData = { test: 'requestData' };
url: 'test-request-data-url',
parameters: {
key1: 'val1',
key2: 'val2',
key3: 'val3',
},
};
const providerName = 'test-credit-provider-name';
const providerStatusUrl = 'test-credit-provider-status-url';
const createCreditRequest = jest.fn().mockName('createCreditRequest'); const createCreditRequest = jest.fn().mockName('createCreditRequest');
hooks.useCreditRequestData.mockReturnValue({
requestData,
createCreditRequest,
});
reduxHooks.useMasqueradeData.mockReturnValue({ isMasquerading: false });
const renderMustRequestContent = () => render( const render = () => {
<IntlProvider locale="en" messages={messages}> el = shallow(<MustRequestContent cardId={cardId} />);
<MustRequestContent cardId={cardId} /> };
</IntlProvider>,
);
describe('MustRequestContent component', () => { describe('MustRequestContent component', () => {
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); render();
hooks.useCreditRequestData.mockReturnValue({
requestData,
createCreditRequest,
});
reduxHooks.useMasqueradeData.mockReturnValue({ isMasquerading: false });
reduxHooks.useCardCreditData.mockReturnValue({
providerName,
providerStatusUrl,
});
}); });
describe('behavior', () => {
describe('hooks', () => {
it('initializes credit request data with cardId', () => { it('initializes credit request data with cardId', () => {
renderMustRequestContent();
expect(hooks.useCreditRequestData).toHaveBeenCalledWith(cardId); expect(hooks.useCreditRequestData).toHaveBeenCalledWith(cardId);
}); });
}); });
describe('render', () => {
describe('behavior', () => { describe('rendered CreditContent component', () => {
describe('rendered content', () => {
beforeEach(() => { beforeEach(() => {
renderMustRequestContent(); component = el.instance.findByType('CreditContent');
}); });
test('action.onClick calls createCreditRequest from useCreditRequestData hook', () => {
it('calls createCreditRequest when request credit button is clicked', async () => { expect(component[0].props.action.onClick).toEqual(createCreditRequest);
const user = userEvent.setup();
const button = screen.getByRole('button', { name: /request credit/i });
await user.click(button);
expect(createCreditRequest).toHaveBeenCalled();
}); });
test('action.message is formatted requestCredit message', () => {
it('shows request credit button that is enabled', () => { expect(component[0].props.action.message).toEqual(
const button = screen.getByRole('button', { name: /request credit/i }); formatMessage(messages.requestCredit),
expect(button).toBeEnabled(); );
}); });
test('action.disabled is false', () => {
it('displays must request message with provider link', () => { expect(component[0].props.action.disabled).toEqual(false);
expect(screen.getByTestId('credit-msg')).toHaveTextContent(/request credit/i);
}); });
test('message is formatted mustRequest message', () => {
it('renders credit request form with correct data', () => { expect(component[0].props.message).toEqual(
const { container } = renderMustRequestContent(); formatMessage(messages.mustRequest, {
const form = container.querySelector('form'); linkToProviderSite: <ProviderLink cardId={cardId} />,
expect(form).toBeInTheDocument(); requestCredit: <b>{formatMessage(messages.requestCredit)}</b>,
expect(form).toHaveAttribute('action', requestData.url); }),
);
}); });
}); test('requestData drawn from useCreditRequestData hook', () => {
expect(component[0].props.requestData).toEqual(requestData);
describe('when masquerading', () => {
beforeEach(() => {
reduxHooks.useMasqueradeData.mockReturnValue({ isMasquerading: true });
renderMustRequestContent();
});
it('disables the request credit button', () => {
const button = screen.getByRole('button', { name: /request credit/i });
expect(button).toHaveClass('disabled');
expect(button).toHaveAttribute('aria-disabled', 'true');
}); });
}); });
}); });

View File

@@ -1,6 +1,7 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import { IntlProvider } from '@edx/frontend-platform/i18n'; import { shallow } from '@edx/react-unit-test-utils';
import { formatMessage } from 'testUtils';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import messages from './messages'; import messages from './messages';
@@ -9,6 +10,11 @@ import PendingContent from './PendingContent';
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
reduxHooks: { useCardCreditData: jest.fn(), useMasqueradeData: jest.fn() }, reduxHooks: { useCardCreditData: jest.fn(), useMasqueradeData: jest.fn() },
})); }));
jest.mock('./components/CreditContent', () => 'CreditContent');
jest.mock('./components/ProviderLink', () => 'ProviderLink');
let el;
let component;
const cardId = 'test-card-id'; const cardId = 'test-card-id';
const providerName = 'test-credit-provider-name'; const providerName = 'test-credit-provider-name';
@@ -19,48 +25,38 @@ reduxHooks.useCardCreditData.mockReturnValue({
}); });
reduxHooks.useMasqueradeData.mockReturnValue({ isMasquerading: false }); reduxHooks.useMasqueradeData.mockReturnValue({ isMasquerading: false });
const renderPendingContent = () => render( const render = () => {
<IntlProvider messages={{}} locale="en"> el = shallow(<PendingContent cardId={cardId} />);
<PendingContent cardId={cardId} /> };
</IntlProvider>,
);
describe('PendingContent component', () => { describe('PendingContent component', () => {
describe('hooks', () => { beforeEach(() => {
render();
});
describe('behavior', () => {
it('initializes card credit data with cardId', () => { it('initializes card credit data with cardId', () => {
renderPendingContent();
expect(reduxHooks.useCardCreditData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardCreditData).toHaveBeenCalledWith(cardId);
}); });
}); });
describe('behavior', () => { describe('render', () => {
describe('rendered CreditContent component', () => { describe('rendered CreditContent component', () => {
it('action message is formatted requestCredit message', () => { beforeEach(() => {
renderPendingContent(); component = el.instance.findByType('CreditContent');
const button = screen.getByRole('link', { name: messages.viewDetails.defaultMessage });
expect(button).toBeInTheDocument();
}); });
it('action href will go to provider status site', () => { test('action.href will go to provider status site', () => {
renderPendingContent(); expect(component[0].props.action.href).toEqual(providerStatusUrl);
const button = screen.getByRole('link', { name: messages.viewDetails.defaultMessage });
expect(button).toHaveAttribute('href', providerStatusUrl);
}); });
it('action.disabled is false', () => { test('action.message is formatted requestCredit message', () => {
renderPendingContent(); expect(component[0].props.action.message).toEqual(
const button = screen.getByRole('link', { name: messages.viewDetails.defaultMessage }); formatMessage(messages.viewDetails),
expect(button).not.toHaveClass('disabled'); );
}); });
it('message is formatted pending message with provider name', () => { test('action.disabled is false', () => {
renderPendingContent(); expect(component[0].props.action.disabled).toEqual(false);
const component = screen.getByTestId('credit-msg');
expect(component).toBeInTheDocument();
expect(component).toHaveTextContent(`${providerName} has received`);
}); });
describe('when masqueradeData is true', () => { test('message is formatted pending message', () => {
it('disables the view details button', () => { expect(component[0].props.message).toEqual(
reduxHooks.useMasqueradeData.mockReturnValue({ isMasquerading: true }); formatMessage(messages.received, { providerName }),
renderPendingContent(); );
const button = screen.getByRole('link', { name: messages.viewDetails.defaultMessage });
expect(button).toHaveClass('disabled');
});
}); });
}); });
}); });

View File

@@ -1,7 +1,10 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import { IntlProvider } from '@edx/frontend-platform/i18n'; import { shallow } from '@edx/react-unit-test-utils';
import { formatMessage } from 'testUtils';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import messages from './messages';
import ProviderLink from './components/ProviderLink';
import RejectedContent from './RejectedContent'; import RejectedContent from './RejectedContent';
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
@@ -9,6 +12,8 @@ jest.mock('hooks', () => ({
useCardCreditData: jest.fn(), useCardCreditData: jest.fn(),
}, },
})); }));
jest.mock('./components/CreditContent', () => 'CreditContent');
jest.mock('./components/ProviderLink', () => 'ProviderLink');
const cardId = 'test-card-id'; const cardId = 'test-card-id';
const credit = { const credit = {
@@ -17,27 +22,32 @@ const credit = {
}; };
reduxHooks.useCardCreditData.mockReturnValue(credit); reduxHooks.useCardCreditData.mockReturnValue(credit);
const renderRejectedContent = () => render(<IntlProvider><RejectedContent cardId={cardId} /></IntlProvider>); let el;
let component;
const render = () => { el = shallow(<RejectedContent cardId={cardId} />); };
const loadComponent = () => { component = el.instance.findByType('CreditContent'); };
describe('RejectedContent component', () => { describe('RejectedContent component', () => {
describe('hooks', () => { beforeEach(render);
describe('behavior', () => {
it('initializes credit data with cardId', () => { it('initializes credit data with cardId', () => {
renderRejectedContent();
expect(reduxHooks.useCardCreditData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardCreditData).toHaveBeenCalledWith(cardId);
}); });
}); });
describe('render', () => { describe('render', () => {
describe('rendered CreditContent component', () => { describe('rendered CreditContent component', () => {
it('no action is passed', () => { beforeAll(loadComponent);
renderRejectedContent(); test('no action is passed', () => {
const action = screen.queryByTestId('action-row-btn'); expect(component[0].props.action).toEqual(undefined);
expect(action).not.toBeInTheDocument();
}); });
it('message is formatted rejected message', () => { test('message is formatted rejected message', () => {
renderRejectedContent(); expect(component[0].props.message).toEqual(formatMessage(
const message = screen.getByTestId('credit-msg'); messages.rejected,
expect(message).toBeInTheDocument(); {
expect(message).toHaveTextContent(`${credit.providerName} did not approve your request for course credit.`); linkToProviderSite: <ProviderLink cardId={cardId} />,
providerName: credit.providerName,
},
));
}); });
}); });
}); });

View File

@@ -1,7 +1,9 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import { shallow } from '@edx/react-unit-test-utils';
import CreditContent from './CreditContent'; import CreditContent from './CreditContent';
let el;
const action = { const action = {
href: 'test-action-href', href: 'test-action-href',
onClick: jest.fn().mockName('test-action-onClick'), onClick: jest.fn().mockName('test-action-onClick'),
@@ -13,57 +15,45 @@ const message = 'test-message';
const requestData = { url: 'test-request-data-url', parameters: { key1: 'val1' } }; const requestData = { url: 'test-request-data-url', parameters: { key1: 'val1' } };
const props = { action, message, requestData }; const props = { action, message, requestData };
const renderCreditContent = (data) => render(
<CreditContent {...data} />,
);
describe('CreditContent component', () => { describe('CreditContent component', () => {
describe('render', () => { describe('render', () => {
describe('with action', () => { describe('with action', () => {
it('loads href and message into action row button', () => { beforeEach(() => {
renderCreditContent(props); el = shallow(<CreditContent {...props} />);
const button = screen.getByRole('link', { name: action.message }); });
expect(button).toBeInTheDocument(); test('snapshot', () => {
expect(button).toHaveAttribute('href', action.href); expect(el.snapshot).toMatchSnapshot();
expect(button).not.toHaveAttribute('disabled'); });
it('loads href, onClick, and message into action row button', () => {
const buttonEl = el.instance.findByTestId('action-row-btn')[0];
expect(buttonEl.props.href).toEqual(action.href);
expect(buttonEl.props.onClick).toEqual(action.onClick);
expect(buttonEl.props.disabled).toEqual(action.disabled);
expect(buttonEl.children[0].el).toEqual(action.message);
}); });
it('loads message into credit-msg div', () => { it('loads message into credit-msg div', () => {
renderCreditContent(props); expect(el.instance.findByTestId('credit-msg')[0].children[0].el).toEqual(message);
const creditMsg = screen.getByTestId('credit-msg');
expect(creditMsg).toBeInTheDocument();
expect(creditMsg.innerHTML).toEqual(message);
}); });
it('loads CreditRequestForm with passed requestData', () => { it('loads CreditRequestForm with passed requestData', () => {
const { container } = renderCreditContent(props); expect(el.instance.findByType('CreditRequestForm')[0].props.requestData).toEqual(requestData);
const creditForm = container.querySelector('form');
expect(creditForm).toBeInTheDocument();
expect(creditForm).toHaveAttribute('action', requestData.url);
}); });
it('disables action button when action.disabled is true', () => { test('disables action button when action.disabled is true', () => {
renderCreditContent({ ...props, action: { ...action, disabled: true } }); el = shallow(<CreditContent {...props} action={{ ...action, disabled: true }} />);
const button = screen.getByRole('link', { name: action.message }); expect(el.instance.findByTestId('action-row-btn')[0].props.disabled).toEqual(true);
expect(button).toBeInTheDocument();
expect(button).toHaveClass('disabled');
expect(button).toHaveAttribute('aria-disabled', 'true');
}); });
}); });
describe('without action', () => { describe('without action', () => {
test('snapshot', () => {
el = shallow(<CreditContent {...{ message, requestData }} />);
});
test('snapshot', () => {
expect(el.snapshot).toMatchSnapshot();
});
it('loads message into credit-msg div', () => { it('loads message into credit-msg div', () => {
renderCreditContent({ message, requestData }); expect(el.instance.findByTestId('credit-msg')[0].children[0].el).toEqual(message);
const creditMsg = screen.getByTestId('credit-msg');
expect(creditMsg).toBeInTheDocument();
expect(creditMsg.innerHTML).toEqual(message);
}); });
it('loads CreditRequestForm with passed requestData', () => { it('loads CreditRequestForm with passed requestData', () => {
const { container } = renderCreditContent({ message, requestData }); expect(el.instance.findByType('CreditRequestForm')[0].props.requestData).toEqual(requestData);
const creditForm = container.querySelector('form');
expect(creditForm).toBeInTheDocument();
expect(creditForm).toHaveAttribute('action', requestData.url);
});
it('does not render action row button', () => {
renderCreditContent({ message, requestData });
const button = screen.queryByRole('link', { name: action.message });
expect(button).not.toBeInTheDocument();
}); });
}); });
}); });

View File

@@ -0,0 +1,32 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`CreditRequestForm component render output valid requestData snapshot 1`] = `
<Form
accept-method="UTF-8"
action="test-request-data-url"
className="hidden"
method="POST"
>
<FormControl
as="textarea"
key="key1"
name="key1"
value="val1"
/>
<FormControl
as="textarea"
key="key2"
name="key2"
value="val2"
/>
<FormControl
as="textarea"
key="key3"
name="key3"
value="val3"
/>
<Button
type="submit"
/>
</Form>
`;

View File

@@ -4,12 +4,6 @@ import useCreditRequestFormData from './hooks';
const requestData = 'test-request-data'; const requestData = 'test-request-data';
jest.mock('react', () => ({
...jest.requireActual('react'),
useRef: jest.fn((val) => ({ current: val, useRef: true })),
useEffect: jest.fn((cb, prereqs) => ({ useEffect: { cb, prereqs } })),
}));
let out; let out;
const ref = { const ref = {
current: { click: jest.fn() }, current: { click: jest.fn() },

View File

@@ -1,4 +1,5 @@
import { render } from '@testing-library/react'; import React from 'react';
import { shallow } from '@edx/react-unit-test-utils';
import { keyStore } from 'utils'; import { keyStore } from 'utils';
@@ -10,8 +11,7 @@ jest.mock('./hooks', () => ({
default: jest.fn(), default: jest.fn(),
})); }));
const ref = { current: { click: jest.fn() }, useRef: jest.fn() }; const ref = 'test-ref';
const requestData = { const requestData = {
url: 'test-request-data-url', url: 'test-request-data-url',
parameters: { parameters: {
@@ -25,41 +25,40 @@ const paramKeys = keyStore(requestData.parameters);
useCreditRequestFormData.mockReturnValue({ ref }); useCreditRequestFormData.mockReturnValue({ ref });
const renderForm = (data) => render(<CreditRequestForm requestData={data} />); let el;
const shallowRender = (data) => { el = shallow(<CreditRequestForm requestData={data} />); };
describe('CreditRequestForm component', () => { describe('CreditRequestForm component', () => {
beforeEach(() => { describe('behavior', () => {
jest.clearAllMocks();
});
describe('hooks', () => {
it('initializes ref from hook with requestData', () => { it('initializes ref from hook with requestData', () => {
renderForm(requestData); shallowRender(requestData);
expect(useCreditRequestFormData).toHaveBeenCalledWith(requestData); expect(useCreditRequestFormData).toHaveBeenCalledWith(requestData);
}); });
}); });
describe('render output', () => { describe('render output', () => {
describe('null requestData', () => { describe('null requestData', () => {
it('returns null', () => { it('returns null', () => {
const { container } = renderForm(null); shallowRender(null);
expect(container.firstChild).toBeNull(); expect(el.isEmptyRender()).toEqual(true);
}); });
}); });
describe('valid requestData', () => { describe('valid requestData', () => {
beforeEach(() => {
shallowRender(requestData);
});
test('snapshot', () => {
expect(el.snapshot).toMatchSnapshot();
});
it('loads Form with requestData url', () => { it('loads Form with requestData url', () => {
const { container } = renderForm(requestData); expect(el.instance.findByType('Form')[0].props.action).toEqual(requestData.url);
const creditForm = container.querySelector('form');
expect(creditForm).toBeInTheDocument();
expect(creditForm).toHaveAttribute('action', requestData.url);
}); });
it('loads a textarea form control for each requestData parameter', () => { it('loads a textarea form control for each requestData parameter', () => {
const { container } = renderForm(requestData); const controls = el.instance.findByType('FormControl');
const controls = container.querySelectorAll('textarea'); expect(controls[0].props.name).toEqual(paramKeys.key1);
expect(controls.length).toEqual(Object.keys(requestData.parameters).length); expect(controls[0].props.value).toEqual(requestData.parameters.key1);
expect(controls[0]).toHaveAttribute('name', paramKeys.key1); expect(controls[1].props.name).toEqual(paramKeys.key2);
expect(controls[0]).toHaveValue(requestData.parameters.key1); expect(controls[1].props.value).toEqual(requestData.parameters.key2);
expect(controls[1]).toHaveAttribute('name', paramKeys.key2); expect(controls[2].props.name).toEqual(paramKeys.key3);
expect(controls[1]).toHaveValue(requestData.parameters.key2); expect(controls[2].props.value).toEqual(requestData.parameters.key3);
expect(controls[2]).toHaveAttribute('name', paramKeys.key3);
expect(controls[2]).toHaveValue(requestData.parameters.key3);
}); });
}); });
}); });

View File

@@ -4,6 +4,9 @@ import { render } from '@testing-library/react';
import useCreditRequestFormData from './hooks'; import useCreditRequestFormData from './hooks';
import CreditRequestForm from '.'; import CreditRequestForm from '.';
jest.unmock('@openedx/paragon');
jest.unmock('react');
jest.mock('./hooks', () => ({ jest.mock('./hooks', () => ({
__esModule: true, __esModule: true,
default: jest.fn(), default: jest.fn(),

View File

@@ -1,6 +1,7 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import { shallow } from '@edx/react-unit-test-utils';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import ProviderLink from './ProviderLink'; import ProviderLink from './ProviderLink';
@@ -15,30 +16,27 @@ const credit = {
providerStatusUrl: 'test-credit-provider-status-url', providerStatusUrl: 'test-credit-provider-status-url',
providerName: 'test-credit-provider-name', providerName: 'test-credit-provider-name',
}; };
let el;
const renderProviderLink = () => render(
<IntlProvider locale="en"><ProviderLink cardId={cardId} /></IntlProvider>,
);
describe('ProviderLink component', () => { describe('ProviderLink component', () => {
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks();
reduxHooks.useCardCreditData.mockReturnValue(credit); reduxHooks.useCardCreditData.mockReturnValue(credit);
renderProviderLink(); el = shallow(<ProviderLink cardId={cardId} />);
}); });
describe('hooks', () => { describe('behavior', () => {
it('initializes credit hook with cardId', () => { it('initializes credit hook with cardId', () => {
expect(reduxHooks.useCardCreditData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardCreditData).toHaveBeenCalledWith(cardId);
}); });
}); });
describe('render', () => { describe('render', () => {
test('snapshot', () => {
expect(el.snapshot).toMatchSnapshot();
});
it('passes credit.providerStatusUrl to the hyperlink href', () => { it('passes credit.providerStatusUrl to the hyperlink href', () => {
const providerLink = screen.getByRole('link', { href: credit.providerStatusUrl }); expect(el.instance.findByType('Hyperlink')[0].props.href).toEqual(credit.providerStatusUrl);
expect(providerLink).toBeInTheDocument();
}); });
it('passes providerName for the link message', () => { it('passes providerName for the link message', () => {
const providerLink = screen.getByRole('link', { href: credit.providerStatusUrl }); expect(el.instance.findByType('Hyperlink')[0].children[0].el).toEqual(credit.providerName);
expect(providerLink).toHaveTextContent(credit.providerName);
}); });
}); });
}); });

View File

@@ -0,0 +1,60 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`CreditContent component render with action snapshot 1`] = `
<Fragment>
<div
className="message-copy credit-msg"
data-testid="credit-msg"
>
test-message
</div>
<ActionRow
className="mt-4"
>
<Button
as="a"
className="border-gray-400"
data-testid="action-row-btn"
disabled={false}
href="test-action-href"
onClick={[MockFunction test-action-onClick]}
rel="noopener"
target="_blank"
variant="outline-primary"
>
test-action-message
</Button>
</ActionRow>
<CreditRequestForm
requestData={
{
"parameters": {
"key1": "val1",
},
"url": "test-request-data-url",
}
}
/>
</Fragment>
`;
exports[`CreditContent component render without action snapshot 1`] = `
<Fragment>
<div
className="message-copy credit-msg"
data-testid="credit-msg"
>
test-message
</div>
<CreditRequestForm
requestData={
{
"parameters": {
"key1": "val1",
},
"url": "test-request-data-url",
}
}
/>
</Fragment>
`;

View File

@@ -0,0 +1,11 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ProviderLink component render snapshot 1`] = `
<Hyperlink
href="test-credit-provider-status-url"
rel="noopener"
target="_blank"
>
test-credit-provider-name
</Hyperlink>
`;

View File

@@ -1,11 +1,10 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import { IntlProvider } from '@edx/frontend-platform/i18n'; import { shallow } from '@edx/react-unit-test-utils';
import { formatMessage } from 'testUtils';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import EntitlementBanner from './EntitlementBanner'; import EntitlementBanner from './EntitlementBanner';
import messages from './messages';
jest.mock('components/Banner', () => 'Banner');
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
utilHooks: { utilHooks: {
useFormatDate: () => date => date, useFormatDate: () => date => date,
@@ -19,7 +18,9 @@ jest.mock('hooks', () => ({
}, },
})); }));
const cardId = 'test-card-id'; const cardId = 'my-test-course-number';
let el;
const entitlementData = { const entitlementData = {
isEntitlement: true, isEntitlement: true,
@@ -30,43 +31,33 @@ const entitlementData = {
}; };
const platformData = { supportEmail: 'test-support-email' }; const platformData = { supportEmail: 'test-support-email' };
const renderComponent = (overrides = {}) => { const render = (overrides = {}) => {
const { entitlement = {} } = overrides; const { entitlement = {} } = overrides;
reduxHooks.useCardEntitlementData.mockReturnValueOnce({ ...entitlementData, ...entitlement }); reduxHooks.useCardEntitlementData.mockReturnValueOnce({ ...entitlementData, ...entitlement });
reduxHooks.usePlatformSettingsData.mockReturnValueOnce(platformData); reduxHooks.usePlatformSettingsData.mockReturnValueOnce(platformData);
return render(<IntlProvider locale="en"><EntitlementBanner cardId={cardId} /></IntlProvider>); el = shallow(<EntitlementBanner cardId={cardId} />);
}; };
describe('EntitlementBanner', () => { describe('EntitlementBanner', () => {
it('initializes data with course number from entitlement', () => { test('initializes data with course number from entitlement', () => {
renderComponent(); render();
expect(reduxHooks.useCardEntitlementData).toHaveBeenCalledWith(cardId); expect(reduxHooks.useCardEntitlementData).toHaveBeenCalledWith(cardId);
expect(reduxHooks.useUpdateSelectSessionModalCallback).toHaveBeenCalledWith(cardId); expect(reduxHooks.useUpdateSelectSessionModalCallback).toHaveBeenCalledWith(cardId);
}); });
it('no display if not an entitlement', () => { test('no display if not an entitlement', () => {
renderComponent({ entitlement: { isEntitlement: false } }); render({ entitlement: { isEntitlement: false } });
const banner = screen.queryByRole('alert'); expect(el.isEmptyRender()).toEqual(true);
expect(banner).toBeNull();
}); });
it('renders when no sessions available', () => { test('snapshot: no sessions available', () => {
renderComponent({ entitlement: { isFulfilled: false, hasSessions: false } }); render({ entitlement: { isFulfilled: false, hasSessions: false } });
const banner = screen.getByRole('alert'); expect(el.snapshot).toMatchSnapshot();
expect(banner).toBeInTheDocument();
expect(banner).toHaveClass('alert-warning');
expect(banner.innerHTML).toContain(platformData.supportEmail);
}); });
it('renders when expiration warning', () => { test('snapshot: expiration warning', () => {
renderComponent({ entitlement: { showExpirationWarning: true } }); render({ entitlement: { showExpirationWarning: true } });
const banner = screen.getByRole('alert'); expect(el.snapshot).toMatchSnapshot();
expect(banner).toBeInTheDocument();
expect(banner).toHaveClass('alert-info');
const button = screen.getByRole('button', { name: formatMessage(messages.selectSession) });
expect(button).toBeInTheDocument();
}); });
it('renders expired banner', () => { test('no display if sessions available and not displaying warning', () => {
renderComponent({ entitlement: { isExpired: true } }); render();
const banner = screen.getByRole('alert'); expect(el.isEmptyRender()).toEqual(true);
expect(banner).toBeInTheDocument();
expect(banner.innerHTML).toContain(formatMessage(messages.entitlementExpired));
}); });
}); });

View File

@@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import { ProgramsList } from './ProgramsList'; import { ProgramsList } from './ProgramsList';
@@ -9,23 +9,15 @@ describe('ProgramsList', () => {
title: 'Example Program 1', title: 'Example Program 1',
}, },
{ {
programUrl: 'http://example2.com', programUrl: 'http://example.com',
title: 'Example Program 2', title: 'Example Program 2',
}, },
]; ];
it('renders correctly', () => { it('renders correctly', () => {
render(<ProgramsList programs={programs} />); const wrapper = shallow(<ProgramsList programs={programs} />);
const list = screen.getByRole('list'); expect(wrapper.snapshot).toMatchSnapshot();
expect(list).toBeInTheDocument();
expect(list.children.length).toEqual(programs.length);
});
it('add the links correctly', () => { expect(wrapper.instance.findByType('li').length).toEqual(programs.length);
render(<ProgramsList programs={programs} />);
programs.forEach(program => {
const link = screen.getByRole('link', { name: program.title });
expect(link).toHaveAttribute('href', program.url);
});
}); });
}); });

View File

@@ -0,0 +1,28 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ProgramsList renders correctly 1`] = `
<ul
className="related-programs-list-container"
>
<li
className="my-2"
key="http://example.com"
>
<a
href="http://example.com"
>
Example Program 1
</a>
</li>
<li
className="my-2"
key="http://example.com"
>
<a
href="http://example.com"
>
Example Program 2
</a>
</li>
</ul>
`;

View File

@@ -0,0 +1,29 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`RelatedProgramsBanner render with programs 1`] = `
<Banner
className="bg-white border-top border-bottom mb-0 related-programs-banner"
icon={[MockFunction icons.Program]}
variant="info"
>
<span
className="font-weight-bolder"
>
Related Programs:
</span>
<ProgramsList
programs={
[
{
"title": "Program 1",
"url": "http://example.com/program1",
},
{
"title": "Program 2",
"url": "http://example.com/program2",
},
]
}
/>
</Banner>
`;

View File

@@ -1,9 +1,10 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import RelatedProgramsBanner from '.'; import RelatedProgramsBanner from '.';
jest.mock('./ProgramsList', () => 'ProgramsList');
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
reduxHooks: { reduxHooks: {
useCardRelatedProgramsData: jest.fn(), useCardRelatedProgramsData: jest.fn(),
@@ -11,39 +12,31 @@ jest.mock('hooks', () => ({
})); }));
const cardId = 'test-card-id'; const cardId = 'test-card-id';
const programData = {
list: [
{
title: 'Program 1',
url: 'http://example.com/program1',
},
{
title: 'Program 2',
url: 'http://example.com/program2',
},
],
length: 2,
};
describe('RelatedProgramsBanner', () => { describe('RelatedProgramsBanner', () => {
it('render empty', () => { test('render empty', () => {
reduxHooks.useCardRelatedProgramsData.mockReturnValue({}); reduxHooks.useCardRelatedProgramsData.mockReturnValue({
render(<IntlProvider locale="en"><RelatedProgramsBanner cardId={cardId} /></IntlProvider>); length: 0,
const banner = screen.queryByRole('alert'); });
expect(banner).toBeNull(); const el = shallow(<RelatedProgramsBanner cardId={cardId} />);
expect(el.isEmptyRender()).toEqual(true);
}); });
it('render with programs', () => { test('render with programs', () => {
reduxHooks.useCardRelatedProgramsData.mockReturnValue(programData); reduxHooks.useCardRelatedProgramsData.mockReturnValue({
render(<IntlProvider locale="en"><RelatedProgramsBanner cardId={cardId} /></IntlProvider>); list: [
const list = screen.getByRole('list'); {
expect(list.childElementCount).toBe(programData.list.length); title: 'Program 1',
}); url: 'http://example.com/program1',
},
it('render related programs title', () => { {
reduxHooks.useCardRelatedProgramsData.mockReturnValue(programData); title: 'Program 2',
render(<IntlProvider locale="en"><RelatedProgramsBanner cardId={cardId} /></IntlProvider>); url: 'http://example.com/program2',
const title = screen.getByText('Related Programs:'); },
expect(title).toBeInTheDocument(); ],
length: 2,
});
const el = shallow(<RelatedProgramsBanner cardId={cardId} />);
expect(el.snapshot).toMatchSnapshot();
}); });
}); });

View File

@@ -0,0 +1,205 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`CertificateBanner snapshot is passing and is downloadable 1`] = `
<Banner
icon={[MockFunction icons.CheckCircle]}
variant="success"
>
Congratulations. Your certificate is ready.
</Banner>
`;
exports[`CertificateBanner snapshot is passing and is earned but unavailable 1`] = `
<Banner>
Your grade and certificate will be ready after 10/20/3030.
</Banner>
`;
exports[`CertificateBanner snapshot is passing and not downloadable render empty 1`] = `null`;
exports[`CertificateBanner snapshot is restricted 1`] = `
<Banner
variant="danger"
>
Your Certificate of Achievement is being held pending confirmation that the issuance of your Certificate is in compliance with strict U.S. embargoes on Iran, Cuba, Syria, and Sudan. If you think our system has mistakenly identified you as being connected with one of those countries, please let us know.
</Banner>
`;
exports[`CertificateBanner snapshot is restricted and verified 1`] = `
<Banner
variant="danger"
>
Your Certificate of Achievement is being held pending confirmation that the issuance of your Certificate is in compliance with strict U.S. embargoes on Iran, Cuba, Syria, and Sudan. If you think our system has mistakenly identified you as being connected with one of those countries, please let us know.
If you would like a refund on your Certificate of Achievement, please contact us.
</Banner>
`;
exports[`CertificateBanner snapshot is restricted and verified with billing email 1`] = `
<Banner
variant="danger"
>
Your Certificate of Achievement is being held pending confirmation that the issuance of your Certificate is in compliance with strict U.S. embargoes on Iran, Cuba, Syria, and Sudan. If you think our system has mistakenly identified you as being connected with one of those countries, please let us know.
<format-message-function
message={
{
"defaultMessage": "If you would like a refund on your Certificate of Achievement, please contact our billing address {billingEmail}",
"description": "Message to learners to contact billing for certificate refunds",
"id": "learner-dash.courseCard.banners.certificateRefundContactBilling",
}
}
values={
{
"billingEmail": <MailtoLink
to="billing@email"
>
billing@email
</MailtoLink>,
}
}
/>
</Banner>
`;
exports[`CertificateBanner snapshot is restricted and verified with support and billing email 1`] = `
<Banner
variant="danger"
>
<format-message-function
message={
{
"defaultMessage": "Your Certificate of Achievement is being held pending confirmation that the issuance of your Certificate is in compliance with strict U.S. embargoes on Iran, Cuba, Syria, and Sudan. If you think our system has mistakenly identified you as being connected with one of those countries, please let us know by contacting {supportEmail}.",
"description": "Restricted certificate warning message",
"id": "learner-dash.courseCard.banners.certificateRestricted",
}
}
values={
{
"supportEmail": <MailtoLink
to="suport@email"
>
suport@email
</MailtoLink>,
}
}
/>
<format-message-function
message={
{
"defaultMessage": "If you would like a refund on your Certificate of Achievement, please contact our billing address {billingEmail}",
"description": "Message to learners to contact billing for certificate refunds",
"id": "learner-dash.courseCard.banners.certificateRefundContactBilling",
}
}
values={
{
"billingEmail": <MailtoLink
to="billing@email"
>
billing@email
</MailtoLink>,
}
}
/>
</Banner>
`;
exports[`CertificateBanner snapshot is restricted and verified with support email 1`] = `
<Banner
variant="danger"
>
<format-message-function
message={
{
"defaultMessage": "Your Certificate of Achievement is being held pending confirmation that the issuance of your Certificate is in compliance with strict U.S. embargoes on Iran, Cuba, Syria, and Sudan. If you think our system has mistakenly identified you as being connected with one of those countries, please let us know by contacting {supportEmail}.",
"description": "Restricted certificate warning message",
"id": "learner-dash.courseCard.banners.certificateRestricted",
}
}
values={
{
"supportEmail": <MailtoLink
to="suport@email"
>
suport@email
</MailtoLink>,
}
}
/>
If you would like a refund on your Certificate of Achievement, please contact us.
</Banner>
`;
exports[`CertificateBanner snapshot is restricted with billing email 1`] = `
<Banner
variant="danger"
>
Your Certificate of Achievement is being held pending confirmation that the issuance of your Certificate is in compliance with strict U.S. embargoes on Iran, Cuba, Syria, and Sudan. If you think our system has mistakenly identified you as being connected with one of those countries, please let us know.
</Banner>
`;
exports[`CertificateBanner snapshot is restricted with support email 1`] = `
<Banner
variant="danger"
>
<format-message-function
message={
{
"defaultMessage": "Your Certificate of Achievement is being held pending confirmation that the issuance of your Certificate is in compliance with strict U.S. embargoes on Iran, Cuba, Syria, and Sudan. If you think our system has mistakenly identified you as being connected with one of those countries, please let us know by contacting {supportEmail}.",
"description": "Restricted certificate warning message",
"id": "learner-dash.courseCard.banners.certificateRestricted",
}
}
values={
{
"supportEmail": <MailtoLink
to="suport@email"
>
suport@email
</MailtoLink>,
}
}
/>
</Banner>
`;
exports[`CertificateBanner snapshot not passing and audit 1`] = `
<Banner>
Grade required to pass the course: 0.8%
</Banner>
`;
exports[`CertificateBanner snapshot not passing and has finished 1`] = `
<Banner
variant="warning"
>
You are not eligible for a certificate.
<Hyperlink
destination="progressUrl"
isInline={true}
>
View grades.
</Hyperlink>
</Banner>
`;
exports[`CertificateBanner snapshot not passing and is downloadable 1`] = `
<Banner
icon={[MockFunction icons.CheckCircle]}
variant="success"
>
Congratulations. Your certificate is ready.
</Banner>
`;
exports[`CertificateBanner snapshot not passing and not audit and not finished 1`] = `
<Banner
variant="warning"
>
Grade required for a certificate: 0.8%
</Banner>
`;

View File

@@ -0,0 +1,63 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`CourseBanner audit access expired, can upgrade snapshot: (auditAccessExpired, upgradeToAccess) 1`] = `
<Fragment>
<Banner>
Your audit access to this course has expired.
Upgrade now to access your course again.
</Banner>
</Fragment>
`;
exports[`CourseBanner audit access expired, cannot upgrade snapshot: (auditAccessExpired, findAnotherCourse hyperlink) 1`] = `
<Fragment>
<Banner>
Your audit access to this course has expired.
<Hyperlink
destination=""
isInline={true}
>
Find another course
</Hyperlink>
</Banner>
</Fragment>
`;
exports[`CourseBanner course run active and cannot upgrade snapshot: (upgradseDeadlinePassed, exploreCourseDetails hyperlink) 1`] = `
<Fragment>
<Banner>
Your upgrade deadline for this course has passed. To upgrade, enroll in a session that is farther in the future.
<Hyperlink
destination="marketing-url"
isInline={true}
>
Explore course details.
</Hyperlink>
</Banner>
</Fragment>
`;
exports[`CourseBanner snapshot: stacking banners 1`] = `<Fragment />`;
exports[`CourseBanner staff snapshot: isStaff 1`] = `<Fragment />`;
exports[`CourseBanner too early has start date snapshot 1`] = `
<Fragment>
<Banner>
You can't access this course just yet because the course hasn't started yet. The course will start on 11/11/3030.
</Banner>
</Fragment>
`;
exports[`CourseBanner too early no start date snapshot 1`] = `<Fragment />`;
exports[`CourseBanner unmet prerequisites snapshot: unmetPrerequisites 1`] = `
<Fragment>
<Banner>
You can't access this course just yet because you have not met the pre-requisites.
</Banner>
</Fragment>
`;

View File

@@ -0,0 +1,53 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`EntitlementBanner snapshot: expiration warning 1`] = `
<Banner>
<format-message-function
message={
{
"defaultMessage": "You must {selectSessionButton} by {changeDeadline} to access the course.",
"description": "Entitlement course message when the entitlement is expiring soon.",
"id": "learner-dash.courseCard.banners.entitlementExpiringSoon",
}
}
values={
{
"changeDeadline": "11/11/2022",
"selectSessionButton": <Button
className="m-0 p-0"
onClick={[MockFunction updateSelectSessionModalCallback(my-test-course-number)]}
size="inline"
variant="link"
>
select a session
</Button>,
}
}
/>
</Banner>
`;
exports[`EntitlementBanner snapshot: no sessions available 1`] = `
<Banner
variant="warning"
>
<format-message-function
message={
{
"defaultMessage": "There are no sessions available at the moment. The course team will create new sessions soon. If no sessions appear, please contact {emailLink} for information.",
"description": "Entitlement course message when no sessions are available",
"id": "learner-dash.courseCard.banners.entitlementUnavailable",
}
}
values={
{
"emailLink": <MailtoLink
to="test-support-email"
>
test-support-email
</MailtoLink>,
}
}
/>
</Banner>
`;

View File

@@ -0,0 +1,41 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`CourseCardBanners render with isEnrolled false 1`] = `
<div
className="course-card-banners"
data-testid="CourseCardBanners"
>
<RelatedProgramsBanner
cardId="test-card-id"
/>
<CourseBanner
cardId="test-card-id"
/>
<EntitlementBanner
cardId="test-card-id"
/>
</div>
`;
exports[`CourseCardBanners renders default CourseCardBanners 1`] = `
<div
className="course-card-banners"
data-testid="CourseCardBanners"
>
<RelatedProgramsBanner
cardId="test-card-id"
/>
<CourseBanner
cardId="test-card-id"
/>
<EntitlementBanner
cardId="test-card-id"
/>
<CertificateBanner
cardId="test-card-id"
/>
<CreditBanner
cardId="test-card-id"
/>
</div>
`;

View File

@@ -3,7 +3,7 @@ import PropTypes from 'prop-types';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import CourseBannerSlot from 'plugin-slots/CourseBannerSlot'; import CourseBanner from './CourseBanner';
import CertificateBanner from './CertificateBanner'; import CertificateBanner from './CertificateBanner';
import CreditBanner from './CreditBanner'; import CreditBanner from './CreditBanner';
import EntitlementBanner from './EntitlementBanner'; import EntitlementBanner from './EntitlementBanner';
@@ -14,7 +14,7 @@ export const CourseCardBanners = ({ cardId }) => {
return ( return (
<div className="course-card-banners" data-testid="CourseCardBanners"> <div className="course-card-banners" data-testid="CourseCardBanners">
<RelatedProgramsBanner cardId={cardId} /> <RelatedProgramsBanner cardId={cardId} />
<CourseBannerSlot cardId={cardId} /> <CourseBanner cardId={cardId} />
<EntitlementBanner cardId={cardId} /> <EntitlementBanner cardId={cardId} />
{isEnrolled && <CertificateBanner cardId={cardId} />} {isEnrolled && <CertificateBanner cardId={cardId} />}
{isEnrolled && <CreditBanner cardId={cardId} />} {isEnrolled && <CreditBanner cardId={cardId} />}

View File

@@ -1,23 +1,14 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import CourseCardBanners from '.'; import CourseCardBanners from '.';
jest.mock('./CourseBanner', () => jest.fn(() => <div>CourseBanner</div>)); jest.mock('./CourseBanner', () => 'CourseBanner');
jest.mock('./CertificateBanner', () => jest.fn(() => <div>CertificateBanner</div>)); jest.mock('./CertificateBanner', () => 'CertificateBanner');
jest.mock('./CreditBanner', () => jest.fn(() => <div>CreditBanner</div>)); jest.mock('./CreditBanner', () => 'CreditBanner');
jest.mock('./EntitlementBanner', () => jest.fn(() => <div>EntitlementBanner</div>)); jest.mock('./EntitlementBanner', () => 'EntitlementBanner');
jest.mock('./RelatedProgramsBanner', () => jest.fn(() => <div>RelatedProgramsBanner</div>)); jest.mock('./RelatedProgramsBanner', () => 'RelatedProgramsBanner');
const mockedComponents = [
'CourseBanner',
'CertificateBanner',
'CreditBanner',
'EntitlementBanner',
'RelatedProgramsBanner',
];
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
reduxHooks: { reduxHooks: {
@@ -29,20 +20,13 @@ describe('CourseCardBanners', () => {
const props = { const props = {
cardId: 'test-card-id', cardId: 'test-card-id',
}; };
it('renders default CourseCardBanners', () => { test('renders default CourseCardBanners', () => {
render(<IntlProvider locale="en"><CourseCardBanners {...props} /></IntlProvider>); const wrapper = shallow(<CourseCardBanners {...props} />);
mockedComponents.map((componentName) => { expect(wrapper.snapshot).toMatchSnapshot();
const mockedComponent = screen.getByText(componentName);
return expect(mockedComponent).toBeInTheDocument();
});
}); });
it('render with isEnrolled false', () => { test('render with isEnrolled false', () => {
reduxHooks.useCardEnrollmentData.mockReturnValueOnce({ isEnrolled: false }); reduxHooks.useCardEnrollmentData.mockReturnValueOnce({ isEnrolled: false });
render(<IntlProvider locale="en"><CourseCardBanners {...props} /></IntlProvider>); const wrapper = shallow(<CourseCardBanners {...props} />);
const mockedComponentsIfNotEnrolled = mockedComponents.slice(-2); expect(wrapper.snapshot).toMatchSnapshot();
mockedComponentsIfNotEnrolled.map((componentName) => {
const mockedComponent = screen.getByText(componentName);
return expect(mockedComponent).toBeInTheDocument();
});
}); });
}); });

View File

@@ -6,11 +6,26 @@ const messages = defineMessages({
description: 'Audit access expiration banner message', description: 'Audit access expiration banner message',
defaultMessage: 'Your audit access to this course has expired.', defaultMessage: 'Your audit access to this course has expired.',
}, },
upgradeToAccess: {
id: 'learner-dash.courseCard.banners.upgradeToAccess',
description: 'Upgrade prompt for audit-expired learners that can still upgrade',
defaultMessage: 'Upgrade now to access your course again.',
},
findAnotherCourse: { findAnotherCourse: {
id: 'learner-dash.courseCard.banners.findAnotherCourse', id: 'learner-dash.courseCard.banners.findAnotherCourse',
description: 'Action prompt taking learners to course exploration', description: 'Action prompt taking learners to course exploration',
defaultMessage: 'Find another course', defaultMessage: 'Find another course',
}, },
upgradeDeadlinePassed: {
id: 'learner-dash.courseCard.banners.upgradeDeadlinePassed',
description: 'Audit upgrade deadline passed banner message',
defaultMessage: 'Your upgrade deadline for this course has passed. To upgrade, enroll in a session that is farther in the future.',
},
exploreCourseDetails: {
id: 'learner-dash.courseCard.banners.exploreCourseDetails',
description: 'Action prompt taking learners to course details page',
defaultMessage: 'Explore course details.',
},
certRestricted: { certRestricted: {
id: 'learner-dash.courseCard.banners.certificateRestricted', id: 'learner-dash.courseCard.banners.certificateRestricted',
description: 'Restricted certificate warning message', description: 'Restricted certificate warning message',

View File

@@ -0,0 +1,56 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`CourseCard Details component does not have change session button on regular course 1`] = `
<div>
<span
class="small"
data-testid="CourseCardDetails"
>
provider-name
test-course-number
• access-message
</span>
</div>
`;
exports[`CourseCard Details component has change session button on entitlement course 1`] = `
<div>
<span
class="small"
data-testid="CourseCardDetails"
>
provider-name
test-course-number
• access-message
<button
class="m-0 p-0"
variant="link"
>
change-or-leave-session-message
</button>
</span>
</div>
`;
exports[`CourseCard Details component has change session button on entitlement course but no access message 1`] = `
<div>
<span
class="small"
data-testid="CourseCardDetails"
>
provider-name
test-course-number
<button
class="m-0 p-0"
variant="link"
>
change-or-leave-session-message
</button>
</span>
</div>
`;

View File

@@ -10,8 +10,8 @@ export const useAccessMessage = ({ cardId }) => {
const courseRun = reduxHooks.useCardCourseRunData(cardId); const courseRun = reduxHooks.useCardCourseRunData(cardId);
const formatDate = utilHooks.useFormatDate(); const formatDate = utilHooks.useFormatDate();
if (!courseRun.isStarted) { if (!courseRun.isStarted) {
if (!courseRun.startDate && !courseRun.advertisedStart) { return null; } if (!courseRun.startDate) { return null; }
const startDate = courseRun.advertisedStart ? courseRun.advertisedStart : formatDate(courseRun.startDate); const startDate = formatDate(courseRun.startDate);
return formatMessage(messages.courseStarts, { startDate }); return formatMessage(messages.courseStarts, { startDate });
} }
if (enrollment.isEnrolled) { if (enrollment.isEnrolled) {

View File

@@ -20,16 +20,6 @@ jest.mock('hooks', () => ({
}, },
})); }));
jest.mock('@edx/frontend-platform/i18n', () => {
const { formatMessage } = jest.requireActual('testUtils');
return {
...jest.requireActual('@edx/frontend-platform/i18n'),
useIntl: () => ({
formatMessage,
}),
};
});
const cardId = 'my-test-card-id'; const cardId = 'my-test-card-id';
const courseNumber = 'test-course-number'; const courseNumber = 'test-course-number';
const useAccessMessage = 'test-access-message'; const useAccessMessage = 'test-access-message';

View File

@@ -1,3 +1,7 @@
@import "~@edx/brand/paragon/variables";
@import "~@openedx/paragon/scss/core/core";
@import "~@edx/brand/paragon/overrides";
a.course-card-title { a.course-card-title {
color: var(--pgn-color-black); color: $black;
} }

View File

@@ -1,4 +1,5 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import { render } from '@testing-library/react';
import CourseCardDetails from '.'; import CourseCardDetails from '.';
@@ -47,36 +48,23 @@ describe('CourseCard Details component', () => {
return separatorsCount; return separatorsCount;
}; };
it('has change session button on entitlement course', () => { test('has change session button on entitlement course', () => {
const wrapper = createWrapper(); const wrapper = createWrapper();
const sessionButton = screen.getByRole('button', { name: defaultHooks.changeOrLeaveSessionMessage }); expect(wrapper.container).toMatchSnapshot();
expect(sessionButton).toBeInTheDocument();
const accessMessage = screen.getByText((text) => text.includes(defaultHooks.accessMessage));
expect(accessMessage).toBeInTheDocument();
// it has 3 separator, 4 column // it has 3 separator, 4 column
expect(fetchSeparators(wrapper)).toBe(3); expect(fetchSeparators(wrapper)).toBe(3);
}); });
it('has change session button on entitlement course but no access message', () => { test('has change session button on entitlement course but no access message', () => {
const wrapper = createWrapper({ accessMessage: null }); const wrapper = createWrapper({ accessMessage: null });
const sessionButton = screen.getByRole('button', { name: defaultHooks.changeOrLeaveSessionMessage }); expect(wrapper.container).toMatchSnapshot();
expect(sessionButton).toBeInTheDocument();
const accessMessage = screen.queryByText((text) => text.includes(defaultHooks.accessMessage));
expect(accessMessage).toBeNull();
// it has 2 separator, 3 column // it has 2 separator, 3 column
expect(fetchSeparators(wrapper)).toBe(2); expect(fetchSeparators(wrapper)).toBe(2);
}); });
it('does not have change session button on regular course', () => { test('does not have change session button on regular course', () => {
const wrapper = createWrapper({ isEntitlement: false }); const wrapper = createWrapper({ isEntitlement: false });
const sessionButton = screen.queryByRole('button', { name: defaultHooks.changeOrLeaveSessionMessage }); expect(wrapper.container).toMatchSnapshot();
expect(sessionButton).toBeNull();
const accessMessage = screen.getByText((text) => text.includes(defaultHooks.accessMessage));
expect(accessMessage).toBeInTheDocument();
// it has 2 separator, 3 column // it has 2 separator, 3 column
expect(fetchSeparators(wrapper)).toBe(2); expect(fetchSeparators(wrapper)).toBe(2);
}); });

View File

@@ -20,13 +20,11 @@ export const CourseCardImage = ({ cardId, orientation }) => {
const { isVerified } = reduxHooks.useCardEnrollmentData(cardId); const { isVerified } = reduxHooks.useCardEnrollmentData(cardId);
const { disableCourseTitle } = useActionDisabledState(cardId); const { disableCourseTitle } = useActionDisabledState(cardId);
const handleImageClicked = reduxHooks.useTrackCourseEvent(courseImageClicked, cardId, homeUrl); const handleImageClicked = reduxHooks.useTrackCourseEvent(courseImageClicked, cardId, homeUrl);
const wrapperClassName = `pgn__card-wrapper-image-cap d-inline-block overflow-visible ${orientation}`; const wrapperClassName = `pgn__card-wrapper-image-cap overflow-visible ${orientation}`;
const image = ( const image = (
<> <>
<img <img
// w-100 is necessary for images on Safari, otherwise stretches full height of the image className="pgn__card-image-cap show"
// https://stackoverflow.com/a/44250830
className="pgn__card-image-cap w-100 show"
src={bannerImgSrc} src={bannerImgSrc}
alt={formatMessage(messages.bannerAlt)} alt={formatMessage(messages.bannerAlt)}
/> />

View File

@@ -1,68 +1,61 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { formatMessage } from 'testUtils';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import track from 'tracking';
import useActionDisabledState from './hooks'; import useActionDisabledState from './hooks';
import { CourseCardImage } from './CourseCardImage'; import CourseCardImage from './CourseCardImage';
import messages from '../messages';
const homeUrl = 'https://example.com'; const homeUrl = 'home-url';
const bannerImgSrc = 'banner-img-src.jpg';
jest.mock('hooks', () => ({ jest.mock('tracking', () => ({
reduxHooks: { course: {
useCardCourseData: jest.fn(() => ({ bannerImgSrc })), courseImageClicked: jest.fn().mockName('segment.courseImageClicked'),
useCardCourseRunData: jest.fn(() => ({ homeUrl })),
useCardEnrollmentData: jest.fn(),
useTrackCourseEvent: jest.fn((eventName, cardId, url) => ({
trackCourseEvent: { eventName, cardId, url },
})),
}, },
})); }));
jest.mock('./hooks', () => jest.fn()); jest.mock('hooks', () => ({
reduxHooks: {
useCardCourseData: jest.fn(() => ({ bannerImgSrc: 'banner-img-src' })),
useCardCourseRunData: jest.fn(() => ({ homeUrl })),
useCardEnrollmentData: jest.fn(() => ({ isVerified: true })),
useTrackCourseEvent: jest.fn((eventName, cardId, upgradeUrl) => ({
trackCourseEvent: { eventName, cardId, upgradeUrl },
})),
},
}));
jest.mock('./hooks', () => jest.fn(() => ({ disableCourseTitle: false })));
describe('CourseCardImage', () => { describe('CourseCardImage', () => {
const props = { const props = {
cardId: 'test-card-id', cardId: 'cardId',
orientation: 'horizontal', orientation: 'orientation',
}; };
beforeEach(() => {
it('renders course image with correct attributes', () => { jest.clearAllMocks();
useActionDisabledState.mockReturnValue({ disableCourseTitle: true });
reduxHooks.useCardEnrollmentData.mockReturnValue({ isVerified: true });
render(<IntlProvider locale="en"><CourseCardImage {...props} /></IntlProvider>);
const image = screen.getByRole('img', { name: formatMessage(messages.bannerAlt) });
expect(image).toBeInTheDocument();
expect(image.src).toContain(bannerImgSrc);
expect(image.parentElement).toHaveClass('horizontal');
}); });
describe('snapshot', () => {
it('isVerified, should render badge', () => { test('renders clickable link course Image', () => {
useActionDisabledState.mockReturnValue({ disableCourseTitle: false }); const wrapper = shallow(<CourseCardImage {...props} />);
reduxHooks.useCardEnrollmentData.mockReturnValue({ isVerified: true }); expect(wrapper.snapshot).toMatchSnapshot();
render(<IntlProvider locale="en"><CourseCardImage {...props} /></IntlProvider>); expect(wrapper.instance.type).toBe('a');
expect(wrapper.instance.props.onClick).toEqual(
const badge = screen.getByText(formatMessage(messages.verifiedBanner)); reduxHooks.useTrackCourseEvent(
expect(badge).toBeInTheDocument(); track.course.courseImageClicked,
const badgeImg = screen.getByRole('img', { name: formatMessage(messages.verifiedBannerRibbonAlt) }); props.cardId,
expect(badgeImg).toBeInTheDocument(); homeUrl,
),
);
});
test('renders disabled link', () => {
useActionDisabledState.mockReturnValueOnce({ disableCourseTitle: true });
const wrapper = shallow(<CourseCardImage {...props} />);
expect(wrapper.snapshot).toMatchSnapshot();
expect(wrapper.instance.type).toBe('div');
});
}); });
describe('behavior', () => {
it('renders link with correct href if disableCourseTitle is false', () => {
useActionDisabledState.mockReturnValue({ disableCourseTitle: false });
reduxHooks.useCardEnrollmentData.mockReturnValue({ isVerified: false });
render(<IntlProvider locale="en"><CourseCardImage {...props} /></IntlProvider>);
const link = screen.getByRole('link');
expect(link).toHaveAttribute('href', homeUrl);
});
describe('hooks', () => {
it('initializes', () => { it('initializes', () => {
useActionDisabledState.mockReturnValue({ disableCourseTitle: false }); shallow(<CourseCardImage {...props} />);
reduxHooks.useCardEnrollmentData.mockReturnValue({ isVerified: true });
render(<IntlProvider locale="en"><CourseCardImage {...props} /></IntlProvider>);
expect(reduxHooks.useCardCourseData).toHaveBeenCalledWith(props.cardId); expect(reduxHooks.useCardCourseData).toHaveBeenCalledWith(props.cardId);
expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith( expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(
props.cardId, props.cardId,

View File

@@ -2,6 +2,7 @@ import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import * as ReactShare from 'react-share'; import * as ReactShare from 'react-share';
import { StrictDict } from '@edx/react-unit-test-utils';
import { useIntl } from '@edx/frontend-platform/i18n'; import { useIntl } from '@edx/frontend-platform/i18n';
import { Dropdown } from '@openedx/paragon'; import { Dropdown } from '@openedx/paragon';
@@ -10,9 +11,9 @@ import { reduxHooks } from 'hooks';
import messages from './messages'; import messages from './messages';
export const testIds = { export const testIds = StrictDict({
emailSettingsModalToggle: 'emailSettingsModalToggle', emailSettingsModalToggle: 'emailSettingsModalToggle',
}; });
export const SocialShareMenu = ({ cardId, emailSettings }) => { export const SocialShareMenu = ({ cardId, emailSettings }) => {
const { formatMessage } = useIntl(); const { formatMessage } = useIntl();

View File

@@ -1,19 +1,32 @@
import { when } from 'jest-when'; import { when } from 'jest-when';
import * as ReactShare from 'react-share';
import { IntlProvider } from '@edx/frontend-platform/i18n'; import { useIntl } from '@edx/frontend-platform/i18n';
import { render, screen } from '@testing-library/react'; import { formatMessage, shallow } from '@edx/react-unit-test-utils';
import track from 'tracking'; import track from 'tracking';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import { useEmailSettings } from './hooks'; import { useEmailSettings } from './hooks';
import SocialShareMenu from './SocialShareMenu'; import SocialShareMenu, { testIds } from './SocialShareMenu';
import messages from './messages'; import messages from './messages';
jest.mock('react-share', () => ({
FacebookShareButton: () => 'FacebookShareButton',
TwitterShareButton: () => 'TwitterShareButton',
}));
jest.mock('tracking', () => ({ jest.mock('tracking', () => ({
socialShare: 'test-social-share-key', socialShare: 'test-social-share-key',
})); }));
jest.mock('@edx/frontend-platform/i18n', () => ({
...jest.requireActual('@edx/frontend-platform/i18n'),
useIntl: jest.fn().mockReturnValue({
formatMessage: jest.requireActual('@edx/react-unit-test-utils').formatMessage,
}),
}));
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
reduxHooks: { reduxHooks: {
useMasqueradeData: jest.fn(), useMasqueradeData: jest.fn(),
@@ -34,9 +47,9 @@ const props = {
const mockHook = (fn, returnValue, options = {}) => { const mockHook = (fn, returnValue, options = {}) => {
if (options.isCardHook) { if (options.isCardHook) {
when(fn).calledWith(props.cardId).mockReturnValue(returnValue); when(fn).calledWith(props.cardId).mockReturnValueOnce(returnValue);
} else { } else {
when(fn).calledWith().mockReturnValue(returnValue); when(fn).calledWith().mockReturnValueOnce(returnValue);
} }
}; };
@@ -76,13 +89,19 @@ const mockHooks = (returnVals = {}) => {
); );
}; };
const renderComponent = () => render(<IntlProvider locale="en"><SocialShareMenu {...props} /></IntlProvider>); let el;
const render = () => {
el = shallow(<SocialShareMenu {...props} />);
};
describe('SocialShareMenu', () => { describe('SocialShareMenu', () => {
describe('behavior', () => { describe('behavior', () => {
beforeEach(() => { beforeEach(() => {
mockHooks(); mockHooks();
renderComponent(); render();
});
it('initializes intl hook', () => {
expect(useIntl).toHaveBeenCalledWith();
}); });
it('initializes local hooks', () => { it('initializes local hooks', () => {
when(useEmailSettings).expectCalledWith(); when(useEmailSettings).expectCalledWith();
@@ -99,43 +118,53 @@ describe('SocialShareMenu', () => {
describe('render', () => { describe('render', () => {
it('renders null if exec ed course', () => { it('renders null if exec ed course', () => {
mockHooks({ isExecEd2UCourse: true }); mockHooks({ isExecEd2UCourse: true });
renderComponent(); render();
const emailSettingsButton = screen.queryByRole('button', { name: messages.emailSettings.defaultMessage }); expect(el.isEmptyRender()).toEqual(true);
expect(emailSettingsButton).toBeNull();
const facebookShareButton = screen.queryByRole('button', { name: 'facebook' });
expect(facebookShareButton).toBeNull();
const twitterShareButton = screen.queryByRole('button', { name: 'twitter' });
expect(twitterShareButton).toBeNull();
}); });
const testEmailSettingsDropdown = (isMasquerading = false) => { const testEmailSettingsDropdown = (isMasquerading = false) => {
describe('email settings dropdown', () => { describe('email settings dropdown', () => {
const loadToggle = () => el.instance.findByTestId(testIds.emailSettingsModalToggle)[0];
it('renders', () => { it('renders', () => {
const emailSettingsButton = screen.getByRole('button', { name: messages.emailSettings.defaultMessage }); expect(el.instance.findByTestId(testIds.emailSettingsModalToggle).length).toEqual(1);
expect(emailSettingsButton).toBeInTheDocument();
}); });
if (isMasquerading) { if (isMasquerading) {
it('is disabled', () => { it('is disabled', () => {
const emailSettingsButton = screen.getByRole('button', { name: messages.emailSettings.defaultMessage }); expect(loadToggle().props.disabled).toEqual(true);
expect(emailSettingsButton).toHaveAttribute('aria-disabled', 'true');
}); });
} else { } else {
it('is enabled', () => { it('is enabled', () => {
const emailSettingsButton = screen.getByRole('button', { name: messages.emailSettings.defaultMessage }); expect(loadToggle().props.disabled).toEqual(false);
expect(emailSettingsButton).toBeEnabled();
}); });
} }
test('show email settings modal on click', () => {
expect(loadToggle().props.onClick).toEqual(props.emailSettings.show);
});
}); });
}; };
const testFacebookShareButton = () => { const testFacebookShareButton = () => {
it('renders facebook share button', () => { test('renders facebook share button with courseName and brand', () => {
const facebookShareButton = screen.getByRole('button', { name: 'facebook' }); const button = el.instance.findByType(ReactShare.FacebookShareButton)[0];
expect(facebookShareButton).toBeInTheDocument(); expect(button.props.url).toEqual(socialShare.facebook.shareUrl);
expect(button.props.onClick).toEqual(
reduxHooks.useTrackCourseEvent(track.socialShare, props.cardId, 'facebook'),
);
expect(button.props.title).toEqual(formatMessage(messages.shareQuote, {
courseName,
socialBrand: socialShare.facebook.socialBrand,
}));
}); });
}; };
const testTwitterShareButton = () => { const testTwitterShareButton = () => {
it('renders twitter share button', () => { test('renders twitter share button with courseName and brand', () => {
const twitterShareButton = screen.getByRole('button', { name: 'twitter' }); const button = el.instance.findByType(ReactShare.TwitterShareButton)[0];
expect(twitterShareButton).toBeInTheDocument(); expect(button.props.url).toEqual(socialShare.twitter.shareUrl);
expect(button.props.onClick).toEqual(
reduxHooks.useTrackCourseEvent(track.socialShare, props.cardId, 'twitter'),
);
expect(button.props.title).toEqual(formatMessage(messages.shareQuote, {
courseName,
socialBrand: socialShare.twitter.socialBrand,
}));
}); });
}; };
describe('all enabled', () => { describe('all enabled', () => {
@@ -145,7 +174,19 @@ describe('SocialShareMenu', () => {
twitter: { isEnabled: true }, twitter: { isEnabled: true },
isEmailEnabled: true, isEmailEnabled: true,
}); });
renderComponent(); render();
});
describe('email settings dropdown', () => {
const loadToggle = () => el.instance.findByTestId(testIds.emailSettingsModalToggle)[0];
it('renders', () => {
expect(el.instance.findByTestId(testIds.emailSettingsModalToggle).length).toEqual(1);
});
it('is enabled', () => {
expect(loadToggle().props.disabled).toEqual(false);
});
test('show email settings modal on click', () => {
expect(loadToggle().props.onClick).toEqual(props.emailSettings.show);
});
}); });
testEmailSettingsDropdown(); testEmailSettingsDropdown();
testFacebookShareButton(); testFacebookShareButton();
@@ -153,49 +194,42 @@ describe('SocialShareMenu', () => {
}); });
describe('only email enabled', () => { describe('only email enabled', () => {
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks();
mockHooks({ isEmailEnabled: true }); mockHooks({ isEmailEnabled: true });
renderComponent(); render();
}); });
testEmailSettingsDropdown(); testEmailSettingsDropdown();
it('does not render facebook or twitter controls', () => { it('does not render facebook or twitter controls', () => {
const facebookShareButton = screen.queryByRole('button', { name: 'facebook' }); expect(el.instance.findByType(ReactShare.FacebookShareButton).length).toEqual(0);
expect(facebookShareButton).toBeNull(); expect(el.instance.findByType(ReactShare.TwitterShareButton).length).toEqual(0);
const twitterShareButton = screen.queryByRole('button', { name: 'twitter' });
expect(twitterShareButton).toBeNull();
}); });
}); describe('masquerading', () => {
describe('masquerading', () => { beforeEach(() => {
beforeEach(() => { mockHooks({ isEmailEnabled: true, isMasquerading: true });
mockHooks({ isEmailEnabled: true, isMasquerading: true }); render();
renderComponent(); });
testEmailSettingsDropdown(true);
}); });
testEmailSettingsDropdown(true);
}); });
describe('only facebook enabled', () => { describe('only facebook enabled', () => {
beforeEach(() => { beforeEach(() => {
mockHooks({ facebook: { isEnabled: true } }); mockHooks({ facebook: { isEnabled: true } });
renderComponent(); render();
}); });
testFacebookShareButton(); testFacebookShareButton();
it('does not render email or twitter controls', () => { it('does not render email or twitter controls', () => {
const emailSettingsButton = screen.queryByRole('button', { name: messages.emailSettings.defaultMessage }); expect(el.instance.findByTestId(testIds.emailSettingsModalToggle).length).toEqual(0);
expect(emailSettingsButton).toBeNull(); expect(el.instance.findByType(ReactShare.TwitterShareButton).length).toEqual(0);
const twitterShareButton = screen.queryByRole('button', { name: 'twitter' });
expect(twitterShareButton).toBeNull();
}); });
}); });
describe('only twitter enabled', () => { describe('only twitter enabled', () => {
beforeEach(() => { beforeEach(() => {
mockHooks({ twitter: { isEnabled: true } }); mockHooks({ twitter: { isEnabled: true } });
renderComponent(); render();
}); });
testTwitterShareButton(); testTwitterShareButton();
it('does not render email or facebook controls', () => { it('does not render email or facebook controls', () => {
const emailSettingsButton = screen.queryByRole('button', { name: messages.emailSettings.defaultMessage }); expect(el.instance.findByTestId(testIds.emailSettingsModalToggle).length).toEqual(0);
expect(emailSettingsButton).toBeNull(); expect(el.instance.findByType(ReactShare.FacebookShareButton).length).toEqual(0);
const facebookShareButton = screen.queryByRole('button', { name: 'facebook' });
expect(facebookShareButton).toBeNull();
}); });
}); });
}); });

View File

@@ -0,0 +1,81 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`CourseCardMenu render show dropdown hide unenroll item and disable email snapshot 1`] = `
<Fragment>
<Dropdown
onToggle={[MockFunction hooks.handleToggleDropdown]}
>
<Dropdown.Toggle
alt="Course actions dropdown"
as="IconButton"
iconAs="Icon"
id="course-actions-dropdown-test-card-id"
src={[MockFunction icons.MoreVert]}
variant="primary"
/>
<Dropdown.Menu>
<SocialShareMenu
cardId="test-card-id"
emailSettings={
{
"hide": [MockFunction emailSettingHide],
"isVisible": false,
"show": [MockFunction emailSettingShow],
}
}
/>
</Dropdown.Menu>
</Dropdown>
<UnenrollConfirmModal
cardId="test-card-id"
closeModal={[MockFunction unenrollHide]}
show={false}
/>
</Fragment>
`;
exports[`CourseCardMenu render show dropdown show unenroll and enable email snapshot 1`] = `
<Fragment>
<Dropdown
onToggle={[MockFunction hooks.handleToggleDropdown]}
>
<Dropdown.Toggle
alt="Course actions dropdown"
as="IconButton"
iconAs="Icon"
id="course-actions-dropdown-test-card-id"
src={[MockFunction icons.MoreVert]}
variant="primary"
/>
<Dropdown.Menu>
<Dropdown.Item
data-testid="unenrollModalToggle"
disabled={false}
onClick={[MockFunction unenrollShow]}
>
Unenroll
</Dropdown.Item>
<SocialShareMenu
cardId="test-card-id"
emailSettings={
{
"hide": [MockFunction emailSettingHide],
"isVisible": false,
"show": [MockFunction emailSettingShow],
}
}
/>
</Dropdown.Menu>
</Dropdown>
<UnenrollConfirmModal
cardId="test-card-id"
closeModal={[MockFunction unenrollHide]}
show={false}
/>
<EmailSettingsModal
cardId="test-card-id"
closeModal={[MockFunction emailSettingHide]}
show={false}
/>
</Fragment>
`;

View File

@@ -1,15 +1,15 @@
import { useKeyedState, StrictDict } from '@edx/react-unit-test-utils';
import track from 'tracking'; import track from 'tracking';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import { useState } from 'react';
import { StrictDict } from 'utils';
export const state = StrictDict({ export const stateKeys = StrictDict({
isUnenrollConfirmVisible: (val) => useState(val), // eslint-disable-line isUnenrollConfirmVisible: 'isUnenrollConfirmVisible',
isEmailSettingsVisible: (val) => useState(val), // eslint-disable-line isEmailSettingsVisible: 'isEmailSettingsVisible',
}); });
export const useUnenrollData = () => { export const useUnenrollData = () => {
const [isVisible, setIsVisible] = state.isUnenrollConfirmVisible(false); const [isVisible, setIsVisible] = useKeyedState(stateKeys.isUnenrollConfirmVisible, false);
return { return {
show: () => setIsVisible(true), show: () => setIsVisible(true),
hide: () => setIsVisible(false), hide: () => setIsVisible(false),
@@ -18,7 +18,7 @@ export const useUnenrollData = () => {
}; };
export const useEmailSettings = () => { export const useEmailSettings = () => {
const [isVisible, setIsVisible] = state.isEmailSettingsVisible(false); const [isVisible, setIsVisible] = useKeyedState(stateKeys.isEmailSettingsVisible, false);
return { return {
show: () => setIsVisible(true), show: () => setIsVisible(true),
hide: () => setIsVisible(false), hide: () => setIsVisible(false),

View File

@@ -1,6 +1,7 @@
import { mockUseKeyedState } from '@edx/react-unit-test-utils';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import track from 'tracking'; import track from 'tracking';
import { MockUseState } from 'testUtils';
import * as hooks from './hooks'; import * as hooks from './hooks';
@@ -18,7 +19,7 @@ reduxHooks.useTrackCourseEvent.mockReturnValue(trackCourseEvent);
const cardId = 'test-card-id'; const cardId = 'test-card-id';
let out; let out;
const state = new MockUseState(hooks); const state = mockUseKeyedState(hooks.stateKeys);
describe('CourseCardMenu hooks', () => { describe('CourseCardMenu hooks', () => {
beforeEach(() => { beforeEach(() => {
@@ -27,6 +28,7 @@ describe('CourseCardMenu hooks', () => {
}); });
describe('useUnenrollData', () => { describe('useUnenrollData', () => {
beforeEach(() => { beforeEach(() => {
state.mockVals({ isUnenrollConfirmVisible: true });
out = hooks.useUnenrollData(); out = hooks.useUnenrollData();
}); });
describe('behavior', () => { describe('behavior', () => {
@@ -35,6 +37,9 @@ describe('CourseCardMenu hooks', () => {
}); });
}); });
describe('output', () => { describe('output', () => {
test('state is loaded from current state value', () => {
expect(out.isVisible).toEqual(true);
});
test('show sets state value to true', () => { test('show sets state value to true', () => {
out.show(); out.show();
expect(state.setState.isUnenrollConfirmVisible).toHaveBeenCalledWith(true); expect(state.setState.isUnenrollConfirmVisible).toHaveBeenCalledWith(true);
@@ -48,6 +53,7 @@ describe('CourseCardMenu hooks', () => {
describe('useEmailSettings', () => { describe('useEmailSettings', () => {
beforeEach(() => { beforeEach(() => {
state.mockVals({ isEmailSettingsVisible: true });
out = hooks.useEmailSettings(); out = hooks.useEmailSettings();
}); });
describe('behavior', () => { describe('behavior', () => {
@@ -56,6 +62,9 @@ describe('CourseCardMenu hooks', () => {
}); });
}); });
describe('output', () => { describe('output', () => {
test('state is loaded from current state value', () => {
expect(out.isVisible).toEqual(state.values.isEmailSettingsVisible);
});
test('show sets state value to true', () => { test('show sets state value to true', () => {
out.show(); out.show();
expect(state.setState.isEmailSettingsVisible).toHaveBeenCalledWith(true); expect(state.setState.isEmailSettingsVisible).toHaveBeenCalledWith(true);

View File

@@ -1,8 +1,10 @@
import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { useIntl } from '@edx/frontend-platform/i18n'; import { useIntl } from '@edx/frontend-platform/i18n';
import { Dropdown, Icon, IconButton } from '@openedx/paragon'; import { Dropdown, Icon, IconButton } from '@openedx/paragon';
import { MoreVert } from '@openedx/paragon/icons'; import { MoreVert } from '@openedx/paragon/icons';
import { StrictDict } from '@edx/react-unit-test-utils';
import EmailSettingsModal from 'containers/EmailSettingsModal'; import EmailSettingsModal from 'containers/EmailSettingsModal';
import UnenrollConfirmModal from 'containers/UnenrollConfirmModal'; import UnenrollConfirmModal from 'containers/UnenrollConfirmModal';
@@ -17,9 +19,9 @@ import {
import messages from './messages'; import messages from './messages';
export const testIds = { export const testIds = StrictDict({
unenrollModalToggle: 'unenrollModalToggle', unenrollModalToggle: 'unenrollModalToggle',
}; });
export const CourseCardMenu = ({ cardId }) => { export const CourseCardMenu = ({ cardId }) => {
const { formatMessage } = useIntl(); const { formatMessage } = useIntl();

View File

@@ -1,23 +1,26 @@
import { when } from 'jest-when'; import { when } from 'jest-when';
import { render, screen } from '@testing-library/react'; import { Dropdown } from '@openedx/paragon';
import userEvent from '@testing-library/user-event'; import { shallow } from '@edx/react-unit-test-utils';
import { IntlProvider } from '@edx/frontend-platform/i18n'; import { useIntl } from '@edx/frontend-platform/i18n';
import EmailSettingsModal from 'containers/EmailSettingsModal';
import UnenrollConfirmModal from 'containers/UnenrollConfirmModal';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import SocialShareMenu from './SocialShareMenu';
import * as hooks from './hooks'; import * as hooks from './hooks';
import CourseCardMenu from '.'; import CourseCardMenu, { testIds } from '.';
import messages from './messages';
jest.mock('hooks', () => ({ jest.mock('@edx/frontend-platform/i18n', () => ({
reduxHooks: { ...jest.requireActual('@edx/frontend-platform/i18n'),
useMasqueradeData: jest.fn(), useIntl: jest.fn().mockReturnValue({
useCardEnrollmentData: jest.fn(), formatMessage: jest.requireActual('@edx/react-unit-test-utils').formatMessage,
}, }),
})); }));
jest.mock('./SocialShareMenu', () => jest.fn(() => <div>SocialShareMenu</div>)); jest.mock('hooks', () => ({
jest.mock('containers/EmailSettingsModal', () => jest.fn(() => <div>EmailSettingsModal</div>)); reduxHooks: { useMasqueradeData: jest.fn(), useCardEnrollmentData: jest.fn() },
jest.mock('containers/UnenrollConfirmModal', () => jest.fn(() => <div>UnenrollConfirmModal</div>)); }));
jest.mock('./SocialShareMenu', () => 'SocialShareMenu');
jest.mock('./hooks', () => ({ jest.mock('./hooks', () => ({
useEmailSettings: jest.fn(), useEmailSettings: jest.fn(),
useUnenrollData: jest.fn(), useUnenrollData: jest.fn(),
@@ -41,11 +44,13 @@ const unenrollData = {
hide: jest.fn().mockName('unenrollHide'), hide: jest.fn().mockName('unenrollHide'),
}; };
let el;
const mockHook = (fn, returnValue, options = {}) => { const mockHook = (fn, returnValue, options = {}) => {
if (options.isCardHook) { if (options.isCardHook) {
when(fn).calledWith(props.cardId).mockReturnValue(returnValue); when(fn).calledWith(props.cardId).mockReturnValueOnce(returnValue);
} else { } else {
when(fn).calledWith().mockReturnValue(returnValue); when(fn).calledWith().mockReturnValueOnce(returnValue);
} }
}; };
@@ -77,13 +82,18 @@ const mockHooks = (returnVals = {}) => {
); );
}; };
const renderComponent = () => render(<IntlProvider locale="en"><CourseCardMenu {...props} /></IntlProvider>); const render = () => {
el = shallow(<CourseCardMenu {...props} />);
};
describe('CourseCardMenu', () => { describe('CourseCardMenu', () => {
describe('hooks', () => { describe('behavior', () => {
beforeEach(() => { beforeEach(() => {
mockHooks(); mockHooks();
renderComponent(); render();
});
it('initializes intl hook', () => {
expect(useIntl).toHaveBeenCalledWith();
}); });
it('initializes local hooks', () => { it('initializes local hooks', () => {
when(hooks.useEmailSettings).expectCalledWith(); when(hooks.useEmailSettings).expectCalledWith();
@@ -99,30 +109,47 @@ describe('CourseCardMenu', () => {
describe('render', () => { describe('render', () => {
it('renders null if showDropdown is false', () => { it('renders null if showDropdown is false', () => {
mockHooks(); mockHooks();
renderComponent(); render();
const dropdown = screen.queryByRole('button', { name: messages.dropdownAlt.defaultMessage }); expect(el.isEmptyRender()).toEqual(true);
expect(dropdown).toBeNull();
}); });
const testHandleToggle = () => {
it('displays Dropdown with onToggle=handleToggleDropdown', () => {
expect(el.instance.findByType(Dropdown)[0].props.onToggle).toEqual(handleToggleDropdown);
});
};
const testUnenrollConfirmModal = () => {
it('displays UnenrollConfirmModal with cardId and unenrollModal data', () => {
const modal = el.instance.findByType(UnenrollConfirmModal)[0];
expect(modal.props.show).toEqual(unenrollData.isVisible);
expect(modal.props.closeModal).toEqual(unenrollData.hide);
expect(modal.props.cardId).toEqual(props.cardId);
});
};
const testSocialShareMenu = () => {
it('displays SocialShareMenu with cardID and emailSettings', () => {
const menu = el.instance.findByType(SocialShareMenu)[0];
expect(menu.props.cardId).toEqual(props.cardId);
expect(menu.props.emailSettings).toEqual(emailSettings);
});
};
describe('show dropdown', () => { describe('show dropdown', () => {
describe('hide unenroll item and disable email', () => { describe('hide unenroll item and disable email', () => {
it('displays Dropdown and renders SocialShareMenu and UnenrollConfirmModal', async () => { beforeEach(() => {
mockHooks({ mockHooks({ shouldShowDropdown: true });
shouldShowDropdown: true, render();
});
renderComponent();
const user = userEvent.setup();
const dropdown = screen.getByRole('button', { name: messages.dropdownAlt.defaultMessage });
expect(dropdown).toBeInTheDocument();
await user.click(dropdown);
const unenrollOption = screen.queryByRole('button', { name: messages.unenroll.defaultMessage });
expect(unenrollOption).toBeNull();
const socialShareMenu = screen.getByText('SocialShareMenu');
expect(socialShareMenu).toBeInTheDocument();
const unenrollConfirmModal = screen.getByText('UnenrollConfirmModal');
expect(unenrollConfirmModal).toBeInTheDocument();
const emailSettingsModal = screen.queryByText('EmailSettingsModal');
expect(emailSettingsModal).toBeNull();
}); });
test('snapshot', () => {
expect(el.snapshot).toMatchSnapshot();
});
testHandleToggle();
testSocialShareMenu();
it('does not render unenroll modal toggle', () => {
expect(el.instance.findByTestId(testIds.unenrollModalToggle).length).toEqual(0);
});
it('does not render EmailSettingsModal', () => {
expect(el.instance.findByType(EmailSettingsModal).length).toEqual(0);
});
testUnenrollConfirmModal();
}); });
describe('show unenroll and enable email', () => { describe('show unenroll and enable email', () => {
const hookProps = { const hookProps = {
@@ -130,49 +157,57 @@ describe('CourseCardMenu', () => {
isEmailEnabled: true, isEmailEnabled: true,
shouldShowUnenrollItem: true, shouldShowUnenrollItem: true,
}; };
beforeEach(() => {
mockHooks(hookProps);
render();
});
test('snapshot', () => {
expect(el.snapshot).toMatchSnapshot();
});
testHandleToggle();
testSocialShareMenu();
describe('unenroll modal toggle', () => { describe('unenroll modal toggle', () => {
let toggle;
describe('not masquerading', () => { describe('not masquerading', () => {
it('renders all components', async () => { beforeEach(() => {
mockHooks(hookProps); mockHooks(hookProps);
renderComponent(); render();
[toggle] = el.instance.findByTestId(testIds.unenrollModalToggle);
const user = userEvent.setup(); });
const dropdown = screen.getByRole('button', { name: messages.dropdownAlt.defaultMessage }); it('renders unenroll modal toggle', () => {
expect(dropdown).toBeInTheDocument(); expect(el.instance.findByTestId(testIds.unenrollModalToggle).length).toEqual(1);
await user.click(dropdown); });
test('onClick from unenroll modal hook', () => {
const unenrollOption = screen.getByRole('button', { name: messages.unenroll.defaultMessage }); expect(toggle.props.onClick).toEqual(unenrollData.show);
expect(unenrollOption).toBeInTheDocument(); });
const socialShareMenu = screen.getByText('SocialShareMenu'); test('disabled', () => {
expect(socialShareMenu).toBeInTheDocument(); expect(toggle.props.disabled).toEqual(false);
const unenrollConfirmModal = screen.getByText('UnenrollConfirmModal');
expect(unenrollConfirmModal).toBeInTheDocument();
const emailSettingsModal = screen.getByText('EmailSettingsModal');
expect(emailSettingsModal).toBeInTheDocument();
}); });
}); });
describe('masquerading', () => { describe('masquerading', () => {
it('renders but unenroll is disabled', async () => { beforeEach(() => {
mockHooks({ ...hookProps, isMasquerading: true }); mockHooks({ ...hookProps, isMasquerading: true });
renderComponent(); render();
[toggle] = el.instance.findByTestId(testIds.unenrollModalToggle);
const user = userEvent.setup(); });
const dropdown = screen.getByRole('button', { name: messages.dropdownAlt.defaultMessage }); it('renders', () => {
expect(dropdown).toBeInTheDocument(); expect(el.instance.findByTestId(testIds.unenrollModalToggle).length).toEqual(1);
await user.click(dropdown); });
test('onClick from unenroll modal hook', () => {
const unenrollOption = screen.getByRole('button', { name: messages.unenroll.defaultMessage }); expect(toggle.props.onClick).toEqual(unenrollData.show);
expect(unenrollOption).toBeInTheDocument(); });
expect(unenrollOption).toHaveAttribute('aria-disabled', 'true'); test('disabled', () => {
const socialShareMenu = screen.getByText('SocialShareMenu'); expect(toggle.props.disabled).toEqual(true);
expect(socialShareMenu).toBeInTheDocument();
const unenrollConfirmModal = screen.getByText('UnenrollConfirmModal');
expect(unenrollConfirmModal).toBeInTheDocument();
const emailSettingsModal = screen.getByText('EmailSettingsModal');
expect(emailSettingsModal).toBeInTheDocument();
}); });
}); });
}); });
testUnenrollConfirmModal();
it('displays EmaiSettingsModal with cardId and emailSettingsModal data', () => {
const modal = el.instance.findByType(EmailSettingsModal)[0];
expect(modal.props.show).toEqual(emailSettings.isVisible);
expect(modal.props.closeModal).toEqual(emailSettings.hide);
expect(modal.props.cardId).toEqual(props.cardId);
});
}); });
}); });
}); });

View File

@@ -1,10 +1,12 @@
import { render, screen } from '@testing-library/react'; import { shallow } from '@edx/react-unit-test-utils';
import userEvent from '@testing-library/user-event';
import { reduxHooks } from 'hooks'; import { reduxHooks } from 'hooks';
import track from 'tracking'; import track from 'tracking';
import useActionDisabledState from './hooks'; import useActionDisabledState from './hooks';
import CourseCardTitle from './CourseCardTitle'; import CourseCardTitle from './CourseCardTitle';
const homeUrl = 'home-url';
jest.mock('tracking', () => ({ jest.mock('tracking', () => ({
course: { course: {
courseTitleClicked: jest.fn().mockName('segment.courseTitleClicked'), courseTitleClicked: jest.fn().mockName('segment.courseTitleClicked'),
@@ -13,61 +15,53 @@ jest.mock('tracking', () => ({
jest.mock('hooks', () => ({ jest.mock('hooks', () => ({
reduxHooks: { reduxHooks: {
useCardCourseData: jest.fn(), useCardCourseData: jest.fn(() => ({ courseName: 'course-name' })),
useCardCourseRunData: jest.fn(), useCardCourseRunData: jest.fn(() => ({ homeUrl })),
useTrackCourseEvent: jest.fn(), useTrackCourseEvent: jest.fn((eventName, cardId, upgradeUrl) => ({
trackCourseEvent: { eventName, cardId, upgradeUrl },
})),
}, },
})); }));
jest.mock('./hooks', () => jest.fn(() => ({ disableCourseTitle: false }))); jest.mock('./hooks', () => jest.fn(() => ({ disableCourseTitle: false })));
describe('CourseCardTitle', () => { describe('CourseCardTitle', () => {
const props = { const props = {
cardId: 'test-card-id', cardId: 'cardId',
}; };
const courseName = 'Test Course';
const homeUrl = 'http://test.com';
const handleTitleClick = jest.fn();
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
reduxHooks.useCardCourseData.mockReturnValue({ courseName });
reduxHooks.useCardCourseRunData.mockReturnValue({ homeUrl });
reduxHooks.useTrackCourseEvent.mockReturnValue(handleTitleClick);
}); });
describe('snapshot', () => {
it('renders course name as link when not disabled', async () => { test('renders clickable link course title', () => {
useActionDisabledState.mockReturnValue({ disableCourseTitle: false }); const wrapper = shallow(<CourseCardTitle {...props} />);
render(<CourseCardTitle {...props} />); expect(wrapper.snapshot).toMatchSnapshot();
const title = wrapper.instance.findByTestId('CourseCardTitle');
const user = userEvent.setup(); expect(title[0].type).toBe('a');
const link = screen.getByRole('link', { name: courseName }); expect(title[0].props.onClick).toEqual(
expect(link).toHaveAttribute('href', homeUrl); reduxHooks.useTrackCourseEvent(
track.course.courseTitleClicked,
await user.click(link); props.cardId,
expect(handleTitleClick).toHaveBeenCalled(); homeUrl,
),
);
});
test('renders disabled link', () => {
useActionDisabledState.mockReturnValueOnce({ disableCourseTitle: true });
const wrapper = shallow(<CourseCardTitle {...props} />);
expect(wrapper.snapshot).toMatchSnapshot();
const title = wrapper.instance.findByTestId('CourseCardTitle');
expect(title[0].type).toBe('span');
expect(title[0].props.onClick).toBeUndefined();
});
}); });
describe('behavior', () => {
it('renders course name as span when disabled', () => { it('initializes', () => {
useActionDisabledState.mockReturnValue({ disableCourseTitle: true }); shallow(<CourseCardTitle {...props} />);
render(<CourseCardTitle {...props} />); expect(reduxHooks.useCardCourseData).toHaveBeenCalledWith(props.cardId);
expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(
const text = screen.getByText(courseName); props.cardId,
expect(text).toBeInTheDocument(); );
expect(text.tagName.toLowerCase()).toBe('span'); expect(useActionDisabledState).toHaveBeenCalledWith(props.cardId);
}); });
it('uses correct hooks with cardId', () => {
useActionDisabledState.mockReturnValue({ disableCourseTitle: false });
render(<CourseCardTitle {...props} />);
expect(reduxHooks.useCardCourseData).toHaveBeenCalledWith(props.cardId);
expect(reduxHooks.useCardCourseRunData).toHaveBeenCalledWith(props.cardId);
expect(reduxHooks.useTrackCourseEvent).toHaveBeenCalledWith(
track.course.courseTitleClicked,
props.cardId,
homeUrl,
);
}); });
}); });

View File

@@ -0,0 +1,25 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`RelatedProgramsBadge component snapshot: 3 programs 1`] = `
<Fragment>
<Button
className="pl-0 mr-0 justify-content-start align-self-start flex-shrink-1"
data-testid="RelatedProgramsBadge"
onClick={[MockFunction useRelatedProgramsBadge.openModal]}
size="sm"
variant="tertiary"
>
<Icon
className="mr-2 pr-0"
src={[MockFunction icons.Program]}
/>
useRelatedProgramsBadge.programsMessage
</Button>
<RelatedProgramsModal
cardId="test-course-number"
closeModal={[MockFunction useRelatedProgramsBadge.closeModal]}
isOpen={true}
/>
</Fragment>
`;

View File

@@ -12,16 +12,6 @@ jest.mock('hooks', () => ({
}, },
})); }));
jest.mock('@edx/frontend-platform/i18n', () => {
const { formatMessage } = jest.requireActual('testUtils');
return {
...jest.requireActual('@edx/frontend-platform/i18n'),
useIntl: () => ({
formatMessage,
}),
};
});
const cardId = 'test-card-id'; const cardId = 'test-card-id';
const state = new MockUseState(hooks); const state = new MockUseState(hooks);

View File

@@ -1,5 +1,5 @@
import { render, screen } from '@testing-library/react'; import React from 'react';
import { IntlProvider } from '@edx/frontend-platform/i18n'; import { shallow } from '@edx/react-unit-test-utils';
import useRelatedProgramsBadge from './hooks'; import useRelatedProgramsBadge from './hooks';
import RelatedProgramsBadge from '.'; import RelatedProgramsBadge from '.';
@@ -15,21 +15,16 @@ const hookProps = {
programsMessage: 'useRelatedProgramsBadge.programsMessage', programsMessage: 'useRelatedProgramsBadge.programsMessage',
}; };
const cardId = 'test-card-id'; const cardId = 'test-course-number';
describe('RelatedProgramsBadge component', () => { describe('RelatedProgramsBadge component', () => {
it('should not render if no programs', () => { test('empty render: no programs', () => {
useRelatedProgramsBadge.mockReturnValueOnce({ ...hookProps, numPrograms: 0 }); useRelatedProgramsBadge.mockReturnValueOnce({ ...hookProps, numPrograms: 0 });
render(<IntlProvider locale="en"><RelatedProgramsBadge cardId={cardId} /></IntlProvider>); const el = shallow(<RelatedProgramsBadge cardId={cardId} />);
const button = screen.queryByRole('button', { name: hookProps.programsMessage }); expect(el.isEmptyRender()).toEqual(true);
expect(button).toBeNull();
const dialog = screen.queryByRole('dialog');
expect(dialog).toBeNull();
}); });
it('3 programs closed', () => { test('snapshot: 3 programs', () => {
useRelatedProgramsBadge.mockReturnValue({ ...hookProps, isOpen: false }); useRelatedProgramsBadge.mockReturnValueOnce(hookProps);
render(<IntlProvider locale="en"><RelatedProgramsBadge cardId={cardId} /></IntlProvider>); expect(shallow(<RelatedProgramsBadge cardId={cardId} />).snapshot).toMatchSnapshot();
const button = screen.getByRole('button', { name: hookProps.programsMessage });
expect(button).toBeInTheDocument();
}); });
}); });

View File

@@ -0,0 +1,72 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`CourseCardImage snapshot renders clickable link course Image 1`] = `
<a
className="pgn__card-wrapper-image-cap overflow-visible orientation"
href="home-url"
onClick={
{
"trackCourseEvent": {
"cardId": "cardId",
"eventName": [MockFunction segment.courseImageClicked],
"upgradeUrl": "home-url",
},
}
}
tabIndex="-1"
>
<Fragment>
<img
alt="Course thumbnail"
className="pgn__card-image-cap show"
src="banner-img-src"
/>
<span
className="course-card-verify-ribbon-container"
title="You're enrolled as a verified student"
>
<Badge
as="div"
className="w-100"
variant="success"
>
Verified
</Badge>
<img
alt="ID Verified Ribbon/Badge"
src="test-file-stub"
/>
</span>
</Fragment>
</a>
`;
exports[`CourseCardImage snapshot renders disabled link 1`] = `
<div
className="pgn__card-wrapper-image-cap overflow-visible orientation"
>
<Fragment>
<img
alt="Course thumbnail"
className="pgn__card-image-cap show"
src="banner-img-src"
/>
<span
className="course-card-verify-ribbon-container"
title="You're enrolled as a verified student"
>
<Badge
as="div"
className="w-100"
variant="success"
>
Verified
</Badge>
<img
alt="ID Verified Ribbon/Badge"
src="test-file-stub"
/>
</span>
</Fragment>
</div>
`;

Some files were not shown because too many files have changed in this diff Show More