| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844 |
- import { provideHttpClient } from '@angular/common/http';
- import { signal } from '@angular/core';
- import { TestBed } from '@angular/core/testing';
- import { By } from '@angular/platform-browser';
- import { provideRouter, Router } from '@angular/router';
- import { RouterTestingHarness } from '@angular/router/testing';
- import { Observable, of, Subject, throwError } from 'rxjs';
- import { CourseCenterPageComponent } from '../features/course-center/course-center-page.component';
- import { AppointmentPageComponent } from '../features/appointment/appointment-page.component';
- import { LearningPageComponent } from '../features/learning/learning-page.component';
- import { StudyRecordsPageComponent } from '../features/study-records/study-records-page.component';
- import { HomePageComponent } from '../features/home/home-page.component';
- import { routes } from '../app.routes';
- import { ApiService } from './api.service';
- import { ApiEnvelope, AppUser } from './models';
- import { PlatformService } from './platform.service';
- import { SessionService } from './session.service';
- class LearningModulesApiService {
- lastScheduleParams: Record<string, unknown> = {};
- lastNodeParams: Record<string, unknown> = {};
- lastAppointmentCourseParams: Record<string, unknown> = {};
- lastWordParams: Record<string, unknown> = {};
- lastLearningWordUpdate: Record<string, unknown> = {};
- lastMemoryParams: Record<string, unknown> = {};
- lastStandaloneLearningRecord: Record<string, unknown> = {};
- appointmentStatus = 0;
- historyWordAudio = '';
- completionRequests: Record<string, unknown>[] = [];
- completionResponse = new Subject<ApiEnvelope<unknown>>();
- lastAppointmentRecordParams: Record<string, unknown> = {};
- studyUpdates: Record<string, unknown>[] = [];
- studyBatches: any[] = [];
- lastStudyQuery: Record<string, unknown> = {};
- reviewPageResponse: Subject<ApiEnvelope<unknown>> | null = null;
- unitRows: Record<string, unknown>[] = [
- { NodeID: 811, NodeName: 'Unit 1', yx_word: 1, total: 20 },
- { NodeID: 812, NodeName: 'Unit 2', yx_word: 0, total: 18 },
- ];
- get<T>(action: string, params: Record<string, unknown> = {}): Observable<ApiEnvelope<T>> {
- if (action === 'app_account_overview') return this.post<T>(action, params);
- if (action === 'content_list' && params['orders'] === 'NEWID()') {
- return this.result<T>(Array.from({length: 8}, (_, i) => ({GeneralID: 9000 + i, Title: `external-${i}`, sy: `外部释义 ${i}`})));
- }
- if (action === 'content_list' && Number(params['ModelID'] ?? params['modelId']) === 56 && String(params['myfield2']).includes('dsid=')) {
- this.lastAppointmentRecordParams = params;
- if (!String(params['myfield2']).includes('|pl=300')) return throwError(() => new Error('无权查看该学员的内容记录'));
- return this.result<T>([{ GeneralID: 9901 }]);
- }
- if (action === 'app_lesson_study') {
- this.lastStudyQuery = params;
- return this.result<T>({record: {learned: this.studyBatches.filter(b => b.status === 'confirmed').reduce((n, b) => n + b.words.length, 0)}, batches: this.studyBatches, pending: this.studyBatches.filter(b => b.status === 'draft').length});
- }
- if (action === 'e_record_detail') {
- return this.result<T>([{ GeneralID: 1001, NodeID: 811, Title: 'apple', sy: '苹果', check: 0 }]);
- }
- if (action === 'app_lesson_courses') { this.lastAppointmentCourseParams=params; return this.result<T>([{bindingId:'binding-801',kcid:801,Title:'七年级上册',courseName:'七年级上册',syjd:'{}'},{bindingId:'binding-802',kcid:802,Title:'阅读训练',courseName:'阅读训练'}]); }
- if (action === 'e_order_detail') {
- return this.result<T>([{
- GeneralID: 901,
- szyh: 100,
- HoneyName: '张雅茜',
- kcid: 801, bindingId:'binding-801',
- yykcmc: '七年级上册',
- dszt: this.appointmentStatus,
- updatedAt: "2026-10-11T00:00:00Z",
- allowedActions: this.appointmentStatus===0?["start"]:this.appointmentStatus===10?["continue","complete"]:this.appointmentStatus===30?[]:["complete"],
- reviewStatus: "pending",
- dslx: 2,
- bxrq: '2026-08-10',
- sdsd: '19:00',
- jffs: '线上',
- }]);
- }
- if (action === 'content_list' && Number(params['nid']) === 291) {
- return this.result<T>([
- { GeneralID: 201, CreateTime: '2026-08-01 09:30:00', con: '初中英语@Unit 1', xxqs: JSON.stringify([{ Title: 'apple' }]) },
- { GeneralID: 202, CreateTime: '2026-08-04 16:20:00', con: '高中英语@Unit 2' },
- ]);
- }
- if (action === 'content_list' && Number(params['nid']) === 388) {
- return this.result<T>([
- { GeneralID: 100, Title: '张雅茜@历史任务', kywsj: '2026-05-15 09:00', fxzt: 1, yhid: 100, xxjlid: 900 },
- { GeneralID: 101, Title: '张雅茜@任务', kywsj: '2026-08-01 09:00', fxzt: 1, yhid: 100, xxjlid: 900 },
- { GeneralID: 102, Title: '张雅茜@任务', kywsj: '2026-08-02 09:00', fxzt: 0, yhid: 100, xxjlid: 900 },
- ]);
- }
- if (action === 'content_list' && Number(params['nid']) === 3) {
- return this.result<T>([{ GeneralID: 301, Title: '阅读理解专项' }]);
- }
- if (action === 'content_list' && Number(params['nid']) === 389) {
- return this.result<T>([{ GeneralID: 401, df: 18, totalScore: 48, dontKnow: 20, wrong: 10 }]);
- }
- if (action === 'content_list' && Number(params['nid']) === 28) {
- this.lastAppointmentCourseParams = params;
- return this.result<T>([
- { GeneralID: 801, kcid: 801, Title: '初中英语|七年级上册@同步词汇' },
- { GeneralID: 802, kcid: 801, Title2: '【初中英语】阅读训练' },
- ]);
- }
- if (action === 'content_list' && Number(params['ModelID']) === 58) {
- return this.result<T>([{ GeneralID: 701, yhid: 100, kcid: 801, syjd: '{}' }]);
- }
- if (action === 'content_list' && Number(params['nid']) === 29) {
- this.lastScheduleParams = params;
- return this.result<T>([
- { GeneralID: 901, bxrq: '2026-08-10 00:00:00', sdsd: '19:00', Title: '同步伴学', plxm: '张老师', dszt: 10 },
- { GeneralID: 902, bxrq: '2026-08-03 00:00:00', sdsd: '18:00', Title: '历史伴学', plxm: '李老师', dszt: 30 },
- ]);
- }
- if (action === 'node_list' && Number(params['pid']) === 8) {
- return this.result<T>([{ NodeID: 801, NodeName: '小学人教版词库' }]);
- }
- if (action === 'node_list' && Number(params['pid']) === 801) {
- this.lastNodeParams = params;
- return this.result<T>(this.unitRows);
- }
- if (action === 'e_ck_list') {
- this.lastWordParams = params;
- const allWords = Number(params['nids']) === 813
- ? Array.from({ length: 65 }, (_, index) => ({ GeneralID: 2001 + index, NodeID: 813, Title: `word-${index + 1}`, sy: `释义 ${index + 1}` }))
- : [
- { GeneralID: 1001, NodeID: 811, Title: 'apple', sy: 'n. 苹果', yp: 'apple.mp3', w_learned: 1 },
- { GeneralID: 1002, NodeID: 812, Title: 'banana', sy: 'n. 香蕉', yp: 'banana.mp3', w_learned: 0 },
- ];
- const pageIndex = Math.max(1, Number(params['cpage'] ?? 1));
- const pageSize = Math.max(1, Number(params['psize'] ?? 30));
- const result = allWords.slice((pageIndex - 1) * pageSize, pageIndex * pageSize);
- return of({
- retcode: 1,
- result: result as T,
- page: { itemCount: allWords.length, pageCount: Math.ceil(allWords.length / pageSize), pageIndex, pageSize },
- });
- }
- if (action === 'node_get') return this.result<T>([{ NodeID: 3, NodeName: '专项训练' }]);
- if (action === 'vote_ask') return this.result<T>([{ ID: 1, Title: '第一组问题' }]);
- if (action === 'vote_question') {
- return this.result<T>([{ ID: 501, AskID: 1, QType: 1, QTitle: 'apple', QContent: '苹果', QOption: JSON.stringify([{ text: '苹果', value: 1 }]) }]);
- }
- if (action === 'e_words_list') {
- return this.result<T>([{
- GeneralID: 601,
- Title: 'tend@张雅茜',
- detail: [{ GeneralID: 701, Title: 'tend', sy: 'vt.照顾;照料', yp: 'tend.mp3' }],
- }]);
- }
- return this.result<T>([]);
- }
- post<T>(action: string, params: Record<string, unknown> = {}): Observable<ApiEnvelope<T>> {
- if (action === 'stu_record_update_v2') {
- this.studyUpdates.push(params);
- const batchId=String(params['batchId']), words=JSON.parse(String(params['addon'])).xxqs;
- const version=Number(params['expectedVersion']||0)+1;
- this.studyBatches=this.studyBatches.filter(b=>b.batchId!==batchId).concat({batchId,words,status:params['saveMode']==='confirm'?'confirmed':'draft',version,bindingId:'binding-801'});
- return this.result<T>({ GeneralID: 9901, batchVersion:version, learned:new Set(this.studyBatches.filter(b=>b.status==='confirmed').flatMap(b=>b.words.map((w:any)=>w.GeneralID))).size });
- }
- if (action === 'app_lesson_complete') {
- this.completionRequests.push(params);
- return this.completionResponse as Observable<ApiEnvelope<T>>;
- }
- if (action === 'e_add_words') {
- this.lastLearningWordUpdate = params;
- return this.result<T>({ affected: String(params['wordsId'] ?? '').split(',').filter(Boolean).length });
- }
- if (action === 'content_add_zt') {
- this.lastStandaloneLearningRecord = params;
- return this.result<T>({ GeneralID: 9901 });
- }
- if (action === 'e_order_tongji') {
- return this.result<T>({ t30: 4, t60: 6, t_tiyan: 1, t_total: 11, t_shichang: 9, t_yongji: 320 });
- }
- if (action === 'e_user_list') {
- return this.result<T>([{ szyh: 100, honeyname: '张雅茜' }]);
- }
- if (action === 'app_learning_overview') {
- const records = Number(params['studentId']) === 777
- ? Array.from({ length: 45 }, (_, index) => ({
- GeneralID: 5000 + index,
- CreateTime: `2026-08-${String(31 - (index % 20)).padStart(2, '0')} 09:30:00`,
- dqrq: '20260801',
- con: `分页学习记录 ${index + 1}`,
- }))
- : [
- { GeneralID: 201, CreateTime: '2026-08-01 09:30:00', dqrq: '20260801', con: '初中英语@Unit 1', xxqs: JSON.stringify([{ Title: 'apple' }]), readingArticleId: 'readingarticle201', readingCompletedAt: '2026-08-01T03:00:00.000Z' },
- { GeneralID: 202, CreateTime: '2026-08-04 16:20:00', dqrq: '20260804', con: '高中英语@Unit 2', xxqs: JSON.stringify([{ Title: 'banana' }]) },
- ];
- const selected = String(params['date'] ?? '');
- return this.result<T>({
- records: (selected ? records.filter((item) => item.CreateTime.startsWith(selected)) : records).slice((Number(params['page']||1)-1)*20,Number(params['page']||1)*20),
- page:{itemCount:selected?records.filter(item=>item.CreateTime.startsWith(selected)).length:records.length,pageCount:Math.ceil(records.length/20)},
- latestReadingRecord: records[0],
- recordDateCounts: { '2026-08-01': 1, '2026-08-04': 1 },
- scheduleDateCounts: {},
- schedules: [],
- courses: [
- { GeneralID: 801, id: 701, kcid: 801, Title: '初中英语|七年级上册@同步词汇' },
- { GeneralID: 802, id: 702, Title2: '【初中英语】阅读训练', syjd: '{"811":"811@Unit 1@1"}' },
- ],
- refreshedAt: '2026-08-26T00:00:00.000Z',
- });
- }
- if (action === 'app_companion_overview') {
- this.lastScheduleParams = params;
- const schedules = [
- { GeneralID: 901, bxrq: '2026-08-10 00:00:00', sdsd: '19:00', Title: '同步伴学', plxm: '张老师', dszt: 10 },
- { GeneralID: 902, bxrq: '2026-08-03 00:00:00', sdsd: '18:00', Title: '历史伴学', plxm: '李老师', dszt: 30 },
- { GeneralID: 903, bxrq: '2099-01-01 00:00:00', sdsd: '18:00', Title: '未来计划', plxm: '王老师', dszt: 0 },
- ];
- const historySchedules = [
- { GeneralID: 911, bxrq: '2026-07-14 00:00:00', sdsd: '22:00', Title: '谢晨晨(60分钟练习)', plxm: '张老师', dszt: 30 },
- { GeneralID: 912, bxrq: '2026-07-14 00:00:00', sdsd: '17:00', Title: '谢谢(60分钟练习)', plxm: '张老师', dszt: 30 },
- { GeneralID: 913, bxrq: '2026-03-09 00:00:00', sdsd: '10:00', Title: '花花(60分钟练习)', plxm: '张老师', dszt: 30 },
- { GeneralID: 914, bxrq: '2026-01-18 00:00:00', sdsd: '16:30', Title: '小赵(60分钟练习)', plxm: '张老师', dszt: 30 },
- { GeneralID: 915, bxrq: '2026-01-18 00:00:00', sdsd: '16:00', Title: '小黄(60分钟练习)', plxm: '张老师', dszt: 30 },
- ];
- const rangeStart = String(params['rangeStart'] ?? '');
- const rangeEnd = String(params['rangeEnd'] ?? '');
- return this.result<T>({
- courses: [
- { GeneralID: 801, id: 701, kcid: 801, Title: '初中英语|七年级上册@同步词汇' },
- { GeneralID: 802, id: 702, Title2: '【初中英语】阅读训练', syjd: '{"811":"811@Unit 1@1"}' },
- ],
- dates:(params['history']?historySchedules:schedules).map(item=>({date:item.bxrq.slice(0,10),finished:item.dszt>=30?1:0,planned:item.dszt>=30?0:1})),
- schedules: params['history']
- ? historySchedules
- : rangeStart && rangeEnd
- ? schedules.filter((item) => item.bxrq.slice(0, 10) >= rangeStart && item.bxrq.slice(0, 10) <= rangeEnd)
- : schedules,
- refreshedAt: '2026-08-26T00:00:00.000Z',
- });
- }
- if (action === 'app_account_overview') {
- if (Number(params['uid']) === 300) {
- return this.result<T>({
- profile: { userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 },
- coachPanel: { todaySchedules: 2, completedLessons: 8, reviewIncome: 36, reviewRecords: 3, totalLessons: 11, totalHours: 9, course30: 4, course60: 6, trialLessons: 1 },
- refreshedAt: '2026-08-26T00:00:00.000Z',
- });
- }
- return this.result<T>({
- profile: { userId: 100, userName: 'student', honeyName: '张雅茜', groupId: 1 },
- companionSummary: { completedSessions: 1, completedMinutes: 60 },
- antiForgetSummary: { total: 3, completed: 2, progress: 67, todayTotal: 0, todayCompleted: 0, duePending: 1, scheduled: 0, scheduledDays: 3 },
- refreshedAt: '2026-08-26T00:00:00.000Z',
- });
- }
- if (action === 'app_review_page') {
- this.lastMemoryParams=params;
- if (this.reviewPageResponse) return this.reviewPageResponse as Observable<ApiEnvelope<T>>;
- const items=params['scope']==='today' ? [{ GeneralID: 102, Title: '张雅茜@任务', kc_title: '高中英语复习', kywsj: String(params['date'])+' 09:00', fxzt: 0, yhid: 100, xxjlid: 900 }] : [
- { GeneralID: 100, Title: '张雅茜@历史任务', kc_title: '历史复习', kywsj: '2026-05-15 09:00', learned_at: '2026-05-01T01:15:00.000Z', fxzt: 1, yhid: 100, xxjlid: 900 },
- { GeneralID: 101, Title: '张雅茜@任务', kc_title: '初中英语复习', kywsj: '2026-08-01 09:00', learned_at: '2026-07-20T02:20:00.000Z', fxzt: 1, yhid: 100, xxjlid: 900 },
- { GeneralID: 102, Title: '张雅茜@任务', kc_title: '高中英语复习', kywsj: '2026-08-02 09:00', learned_at: '2026-07-20T02:20:00.000Z', fxzt: 0, yhid: 100, xxjlid: 900 },
- ...(Number(params['shouru']) === 1
- ? [{ GeneralID: 103, Title: '李同学@任务', kc_title: '小学英语复习', kywsj: '2026-08-02 10:00', learned_at: '2026-07-21T02:20:00.000Z', fxzt: 0, yhid: 101, xxjlid: 901 }]
- : []),
- ];return this.result<T>({items,page:{itemCount:items.length,pageCount:1},summary:{total:items.length,completed:items.filter(i=>i.fxzt===1).length,due:items.filter(i=>i.fxzt!==1).length,today:0,income:0},dates:items.map(i=>({date:i.kywsj.slice(0,10),total:1,completed:i.fxzt===1?1:0}))});
- }
- if (action === 'e_get_21list') {
- this.lastMemoryParams = params;
- return this.result<T>([
- { GeneralID: 100, Title: '张雅茜@历史任务', kc_title: '历史复习', kywsj: '2026-05-15 09:00', learned_at: '2026-05-01T01:15:00.000Z', fxzt: 1, yhid: 100, xxjlid: 900 },
- { GeneralID: 101, Title: '张雅茜@任务', kc_title: '初中英语复习', kywsj: '2026-08-01 09:00', learned_at: '2026-07-20T02:20:00.000Z', fxzt: 1, yhid: 100, xxjlid: 900 },
- { GeneralID: 102, Title: '张雅茜@任务', kc_title: '高中英语复习', kywsj: '2026-08-02 09:00', learned_at: '2026-07-20T02:20:00.000Z', fxzt: 0, yhid: 100, xxjlid: 900 },
- ...(Number(params['shouru']) === 1
- ? [{ GeneralID: 103, Title: '李同学@任务', kc_title: '小学英语复习', kywsj: '2026-08-02 10:00', learned_at: '2026-07-21T02:20:00.000Z', fxzt: 0, yhid: 101, xxjlid: 901 }]
- : []),
- ]);
- }
- if (action === 'e_record_detail') {
- return of({
- retcode: 1,
- result: [{ GeneralID: 701, Title: 'apple', detail: [{ GeneralID: 701, Title: 'apple', sy: '苹果', yp: this.historyWordAudio }] }],
- addon: [{ if_writing: '0', if_writing_tips: '先回忆单词,再查看释义' }],
- } as unknown as ApiEnvelope<T>);
- }
- return this.result<T>([]);
- }
- assetUrl(path: unknown): string { return String(path ?? ''); }
- private result<T>(result: unknown): Observable<ApiEnvelope<T>> {
- return of({ retcode: 1, result: result as T });
- }
- }
- describe('home learning modules', () => {
- const user = signal<AppUser | null>({ userId: 100, userName: 'student', honeyName: '张雅茜', groupId: 1 });
- const selectedStudent = signal<AppUser | null>(null);
- const session = {
- user,
- token: signal('test-token'),
- student: selectedStudent,
- isLoggedIn: signal(true),
- groupId: signal(1),
- setStudent: (student: AppUser | null) => selectedStudent.set(student),
- patchUser: () => undefined,
- logout: () => undefined,
- };
- beforeEach(() => {
- sessionStorage.removeItem('xiaoshu.learning.teacherTodayReview');
- localStorage.removeItem('xiaoshu.learning.homeDaily.v1');
- spyOn(window, 'confirm').and.returnValue(true);
- // Route tests do not depend on remote audio availability or its error-toast timer.
- spyOn(HTMLMediaElement.prototype, 'play').and.returnValue(Promise.resolve());
- localStorage.removeItem('xiaoshu.learning.300.100.901.unbound.skip_spelling_stage');
- user.set({ userId: 100, userName: 'student', honeyName: '张雅茜', groupId: 1 });
- session.groupId.set(1);
- session.student.set(null);
- TestBed.configureTestingModule({
- providers: [
- provideRouter(routes),
- provideHttpClient(),
- { provide: ApiService, useClass: LearningModulesApiService },
- { provide: SessionService, useValue: session },
- ],
- });
- });
- it('keeps all today tasks cached across navigation and visibility', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const originalPost = api.post.bind(api);
- const post = spyOn(api, 'post').and.callFake((action, params) => {
- if (action !== 'app_review_page') return originalPost(action, params);
- return of({ retcode: 1, result: {
- items: Array.from({length: 7}, (_, i) => ({ GeneralID: 100+i, yhid: 100, Title: '今日学员', kywsj: params?.['date'], fxzt: i === 6 ? 1 : 0 })),
- page: { itemCount: 7, pageCount: 1 }, summary: { total: 7, completed: 1, due: 6, today: 7, income: 0 }, dates: [],
- } }) as never;
- });
- const count = () => post.calls.allArgs().filter(([name]) => name === 'app_review_page').length;
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/home/index');
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.coach-memory-list article').length).toBe(7);
- expect(harness.routeNativeElement?.querySelectorAll('.coach-memory-footer').length).toBe(1);
- expect(harness.routeNativeElement?.textContent).not.toContain('查看今日全部任务');
- document.dispatchEvent(new Event('visibilitychange'));
- await harness.navigateByUrl('/pages/member/starshop');
- await harness.navigateByUrl('/pages/home/index');
- harness.fixture.detectChanges();
- expect(count()).toBe(1);
- expect(harness.routeNativeElement?.querySelector('.coach-memory-state')).toBeNull();
- (harness.routeNativeElement?.querySelector('.coach-memory-refresh') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(count()).toBe(2);
- });
- for (const groupId of [1, 3]) {
- it(`caches homepage overview for role ${groupId} until an explicit refresh`, async () => {
- user.set({ userId: groupId === 3 ? 300 : 100, groupId });
- session.groupId.set(groupId);
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const post = spyOn(api, 'post').and.callThrough();
- const get = spyOn(api, 'get').and.callThrough();
- const count = (action: string) => (action === 'app_account_overview' ? get.calls.allArgs() : post.calls.allArgs()).filter(([name]) => name === action).length;
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/home/index');
- const first = { stats: count('e_order_tongji'), review: count('app_review_page'), balances: count('app_account_overview') };
- document.dispatchEvent(new Event('visibilitychange'));
- await harness.navigateByUrl('/pages/member/starshop');
- await harness.navigateByUrl('/pages/home/index');
- harness.fixture.detectChanges();
- expect(count('e_order_tongji')).toBe(first.stats);
- expect(count('app_review_page')).toBe(first.review);
- expect(count('app_account_overview')).toBe(first.balances);
- expect(harness.routeNativeElement?.textContent).not.toContain('正在同步学习计划');
- const button = harness.routeNativeElement?.querySelector(groupId === 3 ? '.coach-hero .coach-refresh' : '.student-home-refresh') as HTMLButtonElement;
- button.click();
- harness.fixture.detectChanges();
- expect(count('e_order_tongji')).toBe(first.stats + 1);
- expect(count('app_review_page')).toBe(first.review + (groupId === 1 ? 1 : 0));
- expect(count('app_account_overview')).toBe(first.balances + (groupId === 1 ? 1 : 0));
- });
- }
- it('loads the review calendar once per login and refreshes only on an explicit request', async () => {
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const originalPost = api.post.bind(api);
- const post = spyOn(api, 'post').and.callFake((action, params) => originalPost(action, params));
- const count = (action: string) => post.calls.allArgs().filter(([name]) => name === action).length;
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/stu/stu_calendar');
- harness.fixture.detectChanges();
- expect(count('app_review_page')).toBe(1);
- expect(count('app_live_versions')).toBe(0);
- await harness.navigateByUrl('/pages/member/starshop');
- await harness.navigateByUrl('/pages/stu/stu_calendar');
- harness.fixture.detectChanges();
- expect(count('app_review_page')).toBe(1);
- const calendar = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- calendar.retryCalendar();
- harness.fixture.detectChanges();
- expect(count('app_review_page')).toBe(2);
- await harness.navigateByUrl('/pages/member/starshop');
- session.token.set('next-login-token');
- await harness.navigateByUrl('/pages/stu/stu_calendar');
- harness.fixture.detectChanges();
- expect(count('app_review_page')).toBe(3);
- session.token.set('test-token');
- });
- it('silently reveals pending and completed words opened from student learning content', async () => {
- const play = spyOn(TestBed.inject(PlatformService), 'play');
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/his/his');
- (harness.routeNativeElement?.querySelector('.current-learning-list button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- (harness.routeNativeElement?.querySelector('.node-list button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(TestBed.inject(Router).url).toContain('readonly=1');
- const learning = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- for (const [index, meaning] of ['n. 香蕉', 'n. 苹果'].entries()) {
- (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[index] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.audio')).toBeNull();
- expect(harness.routeNativeElement?.textContent).not.toContain('读音');
- const word = harness.routeNativeElement?.querySelector('.word-reveal') as HTMLButtonElement;
- word.click();
- harness.fixture.detectChanges();
- expect(word.textContent).toContain(meaning);
- expect(word.getAttribute('aria-expanded')).toBe('true');
- word.click();
- harness.fixture.detectChanges();
- expect(word.getAttribute('aria-expanded')).toBe('false');
- }
- learning.words().forEach((word) => learning.play(word));
- expect(play).not.toHaveBeenCalled();
- });
- it('pages through all words in a history record without requesting a course unit', async () => {
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const originalPost = api.post.bind(api);
- const post = spyOn(api, 'post').and.callFake((action, params) => action === 'e_record_detail'
- ? of({ retcode: 1, result: Array.from({ length: 31 }, (_, index) => ({
- GeneralID: 700 + index,
- Title: `history-${index + 1}`,
- detail: [{ GeneralID: 700 + index, Title: `history-${index + 1}`, sy: `释义 ${index + 1}` }],
- })), addon: [] } as ApiEnvelope<any>)
- : originalPost(action, params));
- const get = spyOn(api, 'get').and.callThrough();
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/his/his_words?id=201');
- harness.fixture.detectChanges();
- const list = () => harness.routeNativeElement?.querySelectorAll('.readonly-word-list article') ?? [];
- expect(list().length).toBe(30);
- expect(harness.routeNativeElement?.textContent).toContain('共 31 个单词');
- (harness.routeNativeElement?.querySelector('.word-preview-pagination .page-direction:last-of-type') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(list().length).toBe(1);
- expect(list()[0].textContent).toContain('history-31');
- expect(harness.routeNativeElement?.textContent).toContain('2 / 2 页');
- expect(get.calls.allArgs().some(([action]) => action === 'e_ck_list')).toBeFalse();
- expect(post.calls.allArgs().filter(([action]) => action === 'e_record_detail').length).toBe(1);
- (harness.routeNativeElement?.querySelector('.word-preview-pagination .page-direction:first-child') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(list().length).toBe(30);
- expect(list()[0].textContent).toContain('history-1');
- });
- it('plays student history words on click without changing learning records or enabling unit preview audio', async () => {
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- api.historyWordAudio = 'apple.mp3';
- const post = spyOn(api, 'post').and.callThrough();
- const platform = TestBed.inject(PlatformService);
- const play = spyOn(platform, 'play');
- const stopAudio = spyOn(platform, 'stopAudio');
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/his/his');
- (harness.routeNativeElement?.querySelector('.learning-record-card .learning-item') as HTMLElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(TestBed.inject(Router).url).toBe('/pages/his/his_words?id=201');
- expect(play).not.toHaveBeenCalled();
- post.calls.reset();
- const button = harness.routeNativeElement?.querySelector('.history-word-audio') as HTMLButtonElement;
- expect(button.disabled).toBeFalse();
- expect(button.getAttribute('aria-label')).toBe('播放单词读音:apple');
- button.querySelector('strong')!.click();
- (button.querySelector('lucide-icon') as HTMLElement).click();
- expect(play).toHaveBeenCalledTimes(2);
- expect(play.calls.mostRecent().args[0]).toContain('apple.mp3');
- expect(post).not.toHaveBeenCalled();
- const learning = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- learning.words.update((words) => words.map((word) => ({ ...word, audio: '' })));
- harness.fixture.detectChanges();
- expect(button.disabled).toBeTrue();
- expect(harness.routeNativeElement?.textContent).toContain('暂无音频');
- button.click();
- expect(play).toHaveBeenCalledTimes(2);
- stopAudio.calls.reset();
- await harness.navigateByUrl('/pages/home/index');
- expect(stopAudio).toHaveBeenCalled();
- await harness.navigateByUrl('/pages/stu/stu_con?nid=811&readonly=1');
- expect(harness.routeNativeElement?.querySelector('.history-word-audio')).toBeNull();
- const preview = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- preview.words().forEach((word) => preview.play(word));
- expect(play).toHaveBeenCalledTimes(2);
- });
- it('keeps the spoken word among listening choices and discards answers from an earlier question', async () => {
- const prefix = 'xiaoshu.learning.100.100.practice.';
- const selectedWords = [
- { GeneralID: 1001, Title: 'apple', sy: '苹果', yp: 'apple.mp3' },
- { GeneralID: 1002, Title: 'banana', sy: '香蕉', yp: 'banana.mp3' },
- ];
- localStorage.setItem(prefix + 'learn_mode', 'newword');
- localStorage.setItem(prefix + 'choose_newword_learn', JSON.stringify(selectedWords));
- localStorage.setItem(prefix + '_page_word_orilist', JSON.stringify([selectedWords]));
- localStorage.setItem(prefix + '_page_current_learn', '1');
- const responses = [new Subject<ApiEnvelope<any>>(), new Subject<ApiEnvelope<any>>()];
- let requestCount = 0;
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const get = api.get.bind(api);
- spyOn(api, 'get').and.callFake((action, params) => action === 'content_list' && params?.['orders'] === 'NEWID()'
- ? responses[requestCount++] ?? of({ retcode: 1, result: [] } as ApiEnvelope<any>)
- : get(action, params));
- spyOn(TestBed.inject(PlatformService), 'play');
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/stu/stu4');
- const learning = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- const firstWord = learning.current()!;
- const firstResponse = responses[0];
- expect(requestCount).toBe(1);
- expect(learning.choicesLoading()).toBeTrue();
- learning.chooseMeaning(firstWord);
- expect(learning.current()).toBe(firstWord); // Cannot answer while options are loading.
- firstResponse?.next({ retcode: 1, result: Array.from({ length: 8 }, (_, index) => ({
- GeneralID: 301 + index, Title: `extra-${index}`, sy: `干扰项 ${index}`,
- })) });
- expect(learning.choiceOptions().length).toBe(4);
- expect(learning.choiceOptions().filter(option => Number(option.id) >= 301).length).toBeGreaterThanOrEqual(2);
- learning.chooseMeaning(firstWord);
- const secondWord = learning.current()!;
- expect(secondWord.id).not.toBe(firstWord.id);
- expect(requestCount).toBe(1); // Reuse the pool instead of requesting each question.
- firstResponse?.next({ retcode: 1, result: [{ GeneralID: 999, Title: 'stale', sy: '迟到结果' }] });
- expect(learning.choiceOptions().length).toBe(4);
- expect(learning.choiceOptions().some(option => option.id === '999')).toBeFalse();
- expect(learning.choiceOptions().some(option => option.id === secondWord.id)).toBeTrue();
- localStorage.removeItem(prefix + 'learn_mode');
- localStorage.removeItem(prefix + 'choose_newword_learn');
- localStorage.removeItem(prefix + '_page_word_orilist');
- localStorage.removeItem(prefix + '_page_current_learn');
- });
- it('lets a student study selected words from their wordbook while keeping course stages teacher-led', async () => {
- localStorage.removeItem('xiaoshu.learning.100.100.practice.learn_mode');
- localStorage.removeItem('xiaoshu.learning.100.100.practice.choose_newword_learn');
- const harness = await RouterTestingHarness.create();
- const router = TestBed.inject(Router);
- await harness.navigateByUrl('/pages/member/starshop');
- (harness.routeNativeElement?.querySelector('.word-select-list > button') as HTMLButtonElement).click();
- (harness.routeNativeElement?.querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const learning = () => harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- expect(router.url).toContain('/pages/stu/stu_con');
- expect(learning().words().map((word) => word.word)).toEqual(['tend']);
- learning().skipStudyList();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/stu3');
- expect(learning().words().map((word) => word.word)).toEqual(['tend']);
- learning().chooseMatch('left', learning().words()[0]);
- learning().chooseMatch('right', learning().words()[0]);
- learning().continueAfterStage();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/stu4');
- expect(learning().words().map((word) => word.word)).toEqual(['tend']);
- learning().chooseMeaning(learning().words()[0]);
- learning().continueAfterStage();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/stu5');
- for (const letter of learning().current()!.word) {
- const index = learning().letters().findIndex((choice) => !choice.used && choice.value === letter);
- expect(index).toBeGreaterThanOrEqual(0);
- learning().spellLetter(index);
- }
- learning().nextSpellingWord();
- learning().continueAfterStage();
- await harness.fixture.whenStable();
- expect(router.url).toBe('/pages/member/starshop');
- expect(localStorage.getItem('xiaoshu.learning.100.100.practice.learn_mode')).toBeNull();
- await harness.navigateByUrl('/pages/stu/stu_con?nids=811&pnid=801');
- await harness.fixture.whenStable();
- expect(router.url).toBe('/pages/home/cart');
- });
- it('separates unlearned and learned wordbook words while keeping selections across tabs', async () => {
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const get = api.get.bind(api);
- spyOn(api, 'get').and.callFake((action, params) => action === 'e_words_list'
- ? of({ retcode: 1, result: params?.['learningStatus'] === 'completed'
- ? [{ GeneralID: 602, Title: 'prepare@张雅茜', xxcs: 2, detail: [{ GeneralID: 702, Title: 'prepare', sy: '准备' }] }]
- : [{ GeneralID: 601, Title: 'tend@张雅茜', xxcs: 1, detail: [{ GeneralID: 701, Title: 'tend', sy: '照顾' }] }],
- page: { itemCount: 1, pendingCount: 1, completedCount: 1, pageCount: 1, pageIndex: 1, pageSize: 30 } } as ApiEnvelope<any>)
- : get(action, params));
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/member/starshop');
- harness.fixture.detectChanges();
- const tabs = harness.routeNativeElement?.querySelectorAll<HTMLButtonElement>('.word-selection-tabs button') ?? [];
- expect(tabs[0].textContent).toContain('未学习');
- expect(tabs[0].textContent).toContain('1');
- expect(harness.routeNativeElement?.querySelector('.pending-column')?.textContent).toContain('tend');
- (harness.routeNativeElement?.querySelector('.pending-column .word-select-list > button') as HTMLButtonElement).click();
- tabs[1].click();
- harness.fixture.detectChanges();
- expect(tabs[1].textContent).toContain('已学习');
- expect(harness.routeNativeElement?.querySelector('.completed-column')?.textContent).toContain('prepare');
- (harness.routeNativeElement?.querySelector('.completed-column .word-select-list > button') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.selection-header strong')?.textContent).toContain('已选 2 个单词');
- tabs[0].click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.pending-column .word-select-list > button.selected')).not.toBeNull();
- });
- it('pronounces a wordbook word on row click and only once on speaker click', async () => {
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const get = api.get.bind(api);
- spyOn(api, 'get').and.callFake((action, params) => action === 'e_words_list'
- ? of({ retcode: 1, result: [{ GeneralID: 601, xxcs: 1, detail: [{ GeneralID: 701, Title: 'tend', yp: 'UploadFiles/tend.mp3' }] }],
- page: { itemCount: 1, pageCount: 1, pageIndex: 1, pageSize: Number(params?.['psize']) } } as ApiEnvelope<any>)
- : get(action, params));
- const play = spyOn(TestBed.inject(PlatformService), 'play');
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/member/starshop');
- harness.fixture.detectChanges();
- const row = harness.routeNativeElement?.querySelector('.pending-column .word-select-list > button') as HTMLButtonElement;
- row.querySelector('strong')!.click();
- harness.fixture.detectChanges();
- expect(row.classList.contains('selected')).toBeTrue();
- expect(play).toHaveBeenCalledTimes(1);
- expect(play.calls.mostRecent().args[0]).toBe('UploadFiles/tend.mp3');
- expect(play.calls.mostRecent().args[0]).not.toContain('UploadFiles/UploadFiles');
- (row.querySelector('.audio') as HTMLElement).click();
- harness.fixture.detectChanges();
- expect(play).toHaveBeenCalledTimes(2);
- expect(row.classList.contains('selected')).toBeTrue();
- });
- it('shows 30 wordbook words per page while counting every learning status', async () => {
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const get = api.get.bind(api);
- const pending = Array.from({ length: 65 }, (_, index) => ({ GeneralID: 601 + index, xxcs: 1, detail: [{ GeneralID: 701 + index, Title: `pending-${index + 1}` }] }));
- const completed = Array.from({ length: 7 }, (_, index) => ({ GeneralID: 801 + index, xxcs: 2, detail: [{ GeneralID: 901 + index, Title: `completed-${index + 1}` }] }));
- const requests: Record<string, unknown>[] = [];
- spyOn(api, 'get').and.callFake((action, params) => {
- if (action !== 'e_words_list') return get(action, params);
- requests.push(params ?? {});
- const rows = params?.['learningStatus'] === 'completed' ? completed : pending;
- const page = Number(params?.['cpage']);
- const size = Number(params?.['psize']);
- return of({ retcode: 1, result: rows.slice((page - 1) * size, page * size),
- page: { itemCount: rows.length, pendingCount: pending.length, completedCount: completed.length,
- pageCount: Math.ceil(rows.length / size), pageIndex: page, pageSize: size } } as ApiEnvelope<any>);
- });
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/member/starshop');
- harness.fixture.detectChanges();
- const view = () => harness.routeNativeElement!;
- const rows = () => view().querySelectorAll('.pending-column .word-select-list > button');
- expect(requests[0]).toEqual(jasmine.objectContaining({ learningStatus: 'pending', cpage: 1, psize: 30 }));
- expect(rows().length).toBe(30);
- expect(view().querySelectorAll('.word-selection-tabs b')[0].textContent).toContain('65');
- expect(view().querySelectorAll('.word-selection-tabs b')[1].textContent).toContain('7');
- (rows()[0] as HTMLButtonElement).click();
- (view().querySelectorAll('.mobile-pagination button')[1] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(requests[1]).toEqual(jasmine.objectContaining({ learningStatus: 'pending', cpage: 2, psize: 30 }));
- expect(rows().length).toBe(30);
- expect(view().querySelector('.mobile-pagination')?.textContent).toContain('第 2 / 3 页');
- (view().querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(requests[2]).toEqual(jasmine.objectContaining({ learningStatus: 'completed', cpage: 1, psize: 30 }));
- expect(view().querySelectorAll('.completed-column .word-select-list > button').length).toBe(7);
- expect(view().querySelector('.selection-header strong')?.textContent).toContain('已选 1 个单词');
- });
- it('keeps wordbook counts and rows correct when the server only returns the old mixed list', async () => {
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const get = api.get.bind(api);
- const all = Array.from({ length: 139 }, (_, index) => ({
- GeneralID: 601 + index,
- xxcs: 1,
- detail: [{ GeneralID: 701 + index, Title: `word-${index + 1}` }],
- }));
- const requests: Record<string, unknown>[] = [];
- spyOn(api, 'get').and.callFake((action, params) => {
- if (action !== 'e_words_list') return get(action, params);
- requests.push(params ?? {});
- const page = Number(params?.['cpage']);
- const size = Number(params?.['psize']);
- return of({ retcode: 1, result: all.slice((page - 1) * size, page * size),
- page: { itemCount: all.length, pageCount: Math.ceil(all.length / size), pageIndex: page, pageSize: size } } as ApiEnvelope<any>);
- });
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/member/starshop');
- harness.fixture.detectChanges();
- const view = () => harness.routeNativeElement!;
- expect(requests.length).toBe(2);
- expect(requests[0]).toEqual(jasmine.objectContaining({ learningStatus: 'pending', psize: 30 }));
- expect(requests[1]).toEqual(jasmine.objectContaining({ cpage: 1, psize: 500 }));
- expect(view().querySelectorAll('.word-selection-tabs b')[0].textContent).toContain('139');
- expect(view().querySelectorAll('.word-selection-tabs b')[1].textContent).toContain('0');
- expect(view().querySelectorAll('.pending-column .word-select-list > button').length).toBe(30);
- expect(view().querySelector('.pending-column .word-select-list > button')?.textContent).toContain('word-1');
- expect(view().querySelector('.mobile-pagination')?.textContent).toContain('第 1 / 5 页 · 共 139 个单词');
- (view().querySelectorAll('.mobile-pagination button')[1] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(view().querySelector('.mobile-pagination')?.textContent).toContain('第 2 / 5 页');
- (view().querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(view().querySelectorAll('.completed-column .word-select-list > button').length).toBe(0);
- expect(requests.length).toBe(2);
- });
- it('saves completed wordbook study before showing the word in the learned tab', async () => {
- const prefix = 'xiaoshu.learning.100.100.practice.';
- const word = { GeneralID: 701, Title: 'tend', sy: '照顾' };
- localStorage.setItem(prefix + 'learn_mode', JSON.stringify('newword'));
- localStorage.setItem(prefix + 'choose_newword_learn', JSON.stringify([word]));
- localStorage.setItem(prefix + '_page_word_orilist', JSON.stringify([[word]]));
- localStorage.setItem(prefix + '_page_current_learn', JSON.stringify(1));
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const get = api.get.bind(api);
- spyOn(api, 'get').and.callFake((action, params) => action === 'e_words_list'
- ? of({ retcode: 1, result: api.lastLearningWordUpdate['save'] === 1 && params?.['learningStatus'] === 'completed'
- ? [{ GeneralID: 601, Title: 'tend@张雅茜', xxcs: 2, detail: [word] }]
- : api.lastLearningWordUpdate['save'] === 1 ? [] : [{ GeneralID: 601, Title: 'tend@张雅茜', xxcs: 1, detail: [word] }],
- page: { itemCount: params?.['learningStatus'] === 'completed' ? 1 : api.lastLearningWordUpdate['save'] === 1 ? 0 : 1,
- pendingCount: api.lastLearningWordUpdate['save'] === 1 ? 0 : 1, completedCount: api.lastLearningWordUpdate['save'] === 1 ? 1 : 0,
- pageCount: 1, pageIndex: 1, pageSize: 30 } } as ApiEnvelope<any>)
- : get(action, params));
- const harness = await RouterTestingHarness.create();
- const router = TestBed.inject(Router);
- await harness.navigateByUrl('/pages/stu/stu5');
- const learning = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- learning.skipSpellingStage();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(api.lastLearningWordUpdate).toEqual(jasmine.objectContaining({ uid: 100, wordsId: '701', save: 1 }));
- expect(router.url).toBe('/pages/member/starshop');
- const tabs = harness.routeNativeElement?.querySelectorAll<HTMLButtonElement>('.word-selection-tabs button') ?? [];
- expect(tabs[0].textContent).toContain('0');
- tabs[1].click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.completed-column')?.textContent).toContain('tend');
- }, 15000);
- it('skips the entire spelling stage for student wordbook self-study in one click', async () => {
- const prefix = 'xiaoshu.learning.100.100.practice.';
- const words = [
- { GeneralID: 701, Title: 'tend', sy: '照顾' },
- { GeneralID: 702, Title: 'work on', sy: '从事' },
- { GeneralID: 703, Title: 'prepare', sy: '准备' },
- ];
- localStorage.setItem(prefix + 'learn_mode', JSON.stringify('newword'));
- localStorage.setItem(prefix + 'choose_newword_learn', JSON.stringify(words.slice(0, 2)));
- localStorage.setItem(prefix + '_page_word_orilist', JSON.stringify([words.slice(0, 2), words.slice(2)]));
- localStorage.setItem(prefix + '_page_current_learn', JSON.stringify(1));
- const harness = await RouterTestingHarness.create();
- const router = TestBed.inject(Router);
- await harness.navigateByUrl('/pages/stu/stu5');
- harness.fixture.detectChanges();
- const learning = () => harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- expect(learning().words().length).toBe(2);
- expect(learning().currentIndex()).toBe(0);
- const skip = Array.from(harness.routeNativeElement?.querySelectorAll<HTMLButtonElement>('.skippable-spelling-actions button') ?? [])
- .find((button) => button.textContent?.includes('跳到下一关'))!;
- skip.click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/stu_con');
- expect(learning().words().map((word) => word.word)).toEqual(['prepare']);
- learning().skipStudyList();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- learning().chooseMatch('left', learning().words()[0]);
- learning().chooseMatch('right', learning().words()[0]);
- learning().continueAfterStage();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/stu4');
- learning().chooseMeaning(learning().words()[0]);
- learning().continueAfterStage();
- await harness.fixture.whenStable();
- expect(router.url).toBe('/pages/member/starshop');
- expect(localStorage.getItem(prefix + 'learn_mode')).toBeNull();
- }, 15000);
- it('still pronounces pending and completed words when a coach reveals them', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- session.student.set({ userId: 100, userName: 'student', groupId: 1 });
- const play = spyOn(TestBed.inject(PlatformService), 'play');
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/stu/stu_abc?nids=811,812&pnid=801');
- for (const index of [0, 1]) {
- (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[index] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.audio')).not.toBeNull();
- (harness.routeNativeElement?.querySelector('.word-reveal') as HTMLButtonElement).click();
- }
- expect(play).toHaveBeenCalledTimes(2);
- expect(play.calls.argsFor(0)[0]).toContain('banana.mp3');
- expect(play.calls.argsFor(1)[0]).toContain('apple.mp3');
- });
- it('shows named schedule students below the trigger and closes after selection or Escape', async () => {
- user.set({userId:300,userName:'coach',honeyName:'张老师',groupId:3});
- const harness=await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/home/shop');
- const component=harness.fixture.debugElement.query(By.directive(CourseCenterPageComponent)).componentInstance as CourseCenterPageComponent;
- component.serverStudents.set([{id:'100',name:'张雅茜',count:15},{id:'101',name:'花花',count:9},{id:'102',name:' ',count:1}]);
- spyOn(component,'load').and.stub();
- harness.fixture.detectChanges();
- await new Promise(resolve => setTimeout(resolve, 0));
- const trigger=harness.routeNativeElement!.querySelector<HTMLButtonElement>('.student-filter .xs-dropdown-trigger')!;
- expect(trigger.textContent).toContain('全部学员(25)');
- trigger.click();harness.fixture.detectChanges();
- const menu=document.querySelector<HTMLElement>('.xs-dropdown-menu')!;
- expect(menu.textContent).toContain('张雅茜(15)');
- expect(menu.textContent).toContain('学员 102(1)');
- expect(menu.getBoundingClientRect().top).toBeGreaterThan(trigger.getBoundingClientRect().bottom);
- menu.querySelectorAll('button')[2].click();harness.fixture.detectChanges();
- await new Promise(resolve => setTimeout(resolve, 0));
- expect(component.selectedStudent()).toBe('101');
- expect(trigger.textContent).toContain('花花(9)');
- expect(document.querySelector('.xs-dropdown-menu')).toBeNull();
- trigger.click();harness.fixture.detectChanges();
- document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape'}));harness.fixture.detectChanges();
- expect(document.querySelector('.xs-dropdown-menu')).toBeNull();
- });
- it('keeps the anti-forget page visible while a selected date loads locally', async () => {
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/stu/stu_calendar');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const component = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- component.memoryMonth.set(new Date(2026, 8, 1, 12));
- component.memorySelectedDate.set('2026-09-11');
- harness.fixture.detectChanges();
- const response = new Subject<ApiEnvelope<unknown>>();
- api.reviewPageResponse = response;
- (harness.routeNativeElement?.querySelector('[aria-label^="2026-09-12"]') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(api.lastMemoryParams['date']).toBe('2026-09-12');
- expect(harness.routeNativeElement?.querySelector('.memory-overview')).not.toBeNull();
- expect(harness.routeNativeElement?.querySelector('.memory-calendar')).not.toBeNull();
- expect(harness.routeNativeElement?.querySelector('.memory-list-loading')?.textContent).toContain('正在加载当日复习');
- response.next({
- retcode: 1,
- result: {
- items: [{ GeneralID: 120, Title: '张雅茜@任务', kc_title: '9月12日复习', kywsj: '2026-09-12 09:00', fxzt: 0, yhid: 100, xxjlid: 920 }],
- page: { itemCount: 1, pageCount: 1 },
- summary: { total: 1, completed: 0, due: 0, today: 0, income: 0 },
- dates: [{ date: '2026-09-12', total: 1, completed: 0 }],
- },
- });
- response.complete();
- api.reviewPageResponse = null;
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.memory-list-loading')).toBeNull();
- expect(harness.routeNativeElement?.querySelector('.memory-date-tasks')?.textContent).toContain('9月12日复习');
- });
- it('shows a retryable error instead of an empty review when the detail has no words', async () => {
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const post = api.post.bind(api);
- spyOn(api, 'post').and.callFake((action, params) => action === 'e_record_detail'
- ? of({ retcode: 1, result: [], addon: [] } as ApiEnvelope<any>) : post(action, params));
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/stu/record?id=900&gid=102&kcid=801');
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.empty-state.error')?.textContent).toContain('没有读取到单词');
- expect(harness.routeNativeElement?.querySelector('.empty-state.error button')?.textContent).toContain('重新加载');
- expect(harness.routeNativeElement?.querySelector('.record-list')).toBeNull();
- });
- it('syncs a missing learning record and reopens its review words', async () => {
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const post = api.post.bind(api);
- let detailReads = 0;
- spyOn(api, 'post').and.callFake((action, params) => {
- if (action === 'e_record_detail') {
- detailReads += 1;
- return of({ retcode: 1, result: detailReads === 1 ? [] : [{ GeneralID: 701, Title: 'apple', sy: '苹果' }], addon: [] } as ApiEnvelope<any>);
- }
- if (action === 'app_learning_overview') return of({ retcode: 1, result: {} } as ApiEnvelope<any>);
- return post(action, params);
- });
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/stu/record?id=864038&gid=864047&kcid=398');
- harness.fixture.detectChanges();
- expect(detailReads).toBe(2);
- expect(harness.routeNativeElement?.querySelector('.record-word')?.textContent).toContain('apple');
- expect(harness.routeNativeElement?.querySelector('.empty-state.error')).toBeNull();
- });
- it('reads the original word list when the detail stays empty after syncing', async () => {
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const post = api.post.bind(api);
- const get = api.get.bind(api);
- spyOn(api, 'post').and.callFake((action, params) => action === 'e_record_detail'
- ? of({ retcode: 1, result: [], addon: [] } as ApiEnvelope<any>) : action === 'app_learning_overview'
- ? of({ retcode: 1, result: {} } as ApiEnvelope<any>) : post(action, params));
- spyOn(api, 'get').and.callFake((action, params) => action === 'content_get'
- ? of({ retcode: 1, result: [{ GeneralID: 864038, xxqs: JSON.stringify([{ GeneralID: 701, Title: 'apple' }]) }] } as ApiEnvelope<any>)
- : get(action, params));
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/stu/record?id=864038&gid=864047&kcid=398');
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.record-word')?.textContent).toContain('apple');
- expect(harness.routeNativeElement?.querySelector('.empty-state.error')).toBeNull();
- });
- it('identifies a legacy writing review with no original words and keeps it incomplete', async () => {
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const post = api.post.bind(api);
- const get = api.get.bind(api);
- spyOn(api, 'post').and.callFake((action, params) => action === 'e_record_detail'
- ? of({ retcode: 1, result: [], addon: [] } as ApiEnvelope<any>) : action === 'app_learning_overview'
- ? of({ retcode: 1, result: {} } as ApiEnvelope<any>) : post(action, params));
- spyOn(api, 'get').and.callFake((action, params) => action === 'content_get'
- ? of({ retcode: 1, result: [{ GeneralID: 864038, xxqs: '', learned: 0, con: '完成了写作学习' }] } as ApiEnvelope<any>)
- : get(action, params));
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/stu/record?id=864038&gid=864047&kcid=398');
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.textContent).toContain('写作学习记录,原本没有单词');
- expect(harness.routeNativeElement?.querySelector('.record-list')).toBeNull();
- expect(harness.routeNativeElement?.querySelector('a[href="/pages/stu/stu_calendar"]')).not.toBeNull();
- expect(harness.routeNativeElement?.textContent).not.toContain('结束本次复习');
- });
- it('renders source-shaped data for all four home entries', async () => {
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/home/index');
- expect(harness.fixture.nativeElement.querySelector('.tabbar')).not.toBeNull();
- expect(harness.routeNativeElement?.querySelector('.home-header [aria-label="搜索"]')).toBeNull();
- expect(harness.routeNativeElement?.querySelector('.home-header [aria-label="用户中心"]')).toBeNull();
- expect(harness.routeNativeElement?.querySelector('.memory-hero')).not.toBeNull();
- expect(harness.routeNativeElement?.querySelectorAll('.memory-dot').length).toBe(21);
- expect(harness.routeNativeElement?.querySelector('.today-panel')?.textContent).toContain('学习新词');
- expect(harness.routeNativeElement?.querySelectorAll('.student-stats > div').length).toBe(5);
- expect(harness.routeNativeElement?.querySelectorAll('.quick-grid > a').length).toBe(4);
- expect(harness.routeNativeElement?.querySelector('.continue-button')?.getAttribute('href')).toBe('/pages/stu/stu_calendar');
- expect(harness.routeNativeElement?.querySelector('.task-link')?.getAttribute('href')).toBe('/pages/home/cart');
- await harness.navigateByUrl('/pages/stu/index');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(TestBed.inject(Router).url).toBe('/pages/home/cart');
- expect(harness.routeNativeElement?.textContent).not.toContain('选择词库教材');
- await harness.navigateByUrl('/pages/stu/stu_list?nid=801&bindingId=701');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.node-list button').length).toBe(2);
- expect(harness.routeNativeElement?.querySelector('.node-list button')?.textContent).toContain('已学 1/20 · 进度 5%');
- expect(harness.routeNativeElement?.querySelectorAll('.unit-progress-ring').length).toBe(2);
- expect(harness.routeNativeElement?.querySelector('.unit-progress-ring')?.textContent).toContain('5%');
- expect(harness.routeNativeElement?.querySelector('.unit-selection-summary')).toBeNull();
- expect(harness.routeNativeElement?.querySelector('.unit-actions')).toBeNull();
- const firstUnit = harness.routeNativeElement?.querySelector('.node-list button') as HTMLButtonElement;
- firstUnit.click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const readonlyRouter = TestBed.inject(Router);
- expect(readonlyRouter.url).toBe('/pages/stu/stu_abc?nids=811&pnid=801&readonly=1');
- expect(harness.routeNativeElement?.querySelector('.selection-header')?.textContent).toContain('词库学习进度');
- expect(harness.routeNativeElement?.querySelector('.selection-header .primary-button')).toBeNull();
- expect(harness.routeNativeElement?.querySelector('.pending-column')?.textContent).toContain('banana');
- expect(harness.routeNativeElement?.querySelector('.word-select-check')).toBeNull();
- expect(harness.routeNativeElement?.querySelector('.word-assessment')).toBeNull();
- (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.completed-column')?.textContent).toContain('apple');
- expect(harness.routeNativeElement?.querySelector('.pending-column')).toBeNull();
- await harness.navigateByUrl('/pages/home/index');
- await harness.navigateByUrl('/pages/stu/stu_con?nid=813&pnid=801&readonly=1');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const wordApi = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- expect(wordApi.lastWordParams['psize']).toBe(30);
- expect(harness.routeNativeElement?.querySelectorAll('.readonly-word-list article').length).toBe(30);
- expect(harness.routeNativeElement?.querySelector('.readonly-word-header')?.textContent).toContain('第 1–30 条 · 共 65 个单词');
- expect(harness.routeNativeElement?.querySelector('.word-preview-pagination')?.textContent).toContain('1 / 3 页');
- (harness.routeNativeElement?.querySelector('[aria-label="第 2 页"]') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(wordApi.lastWordParams['cpage']).toBe(2);
- expect(harness.routeNativeElement?.querySelectorAll('.readonly-word-list article').length).toBe(30);
- expect(harness.routeNativeElement?.querySelector('.readonly-word-header')?.textContent).toContain('第 31–60 条 · 共 65 个单词');
- expect(harness.routeNativeElement?.querySelector('.readonly-word-list')?.textContent).toContain('word-31');
- expect(harness.routeNativeElement?.querySelector('.word-preview-pagination')?.textContent).toContain('2 / 3 页');
- await harness.navigateByUrl('/pages/stu/stu_list?nid=999&bindingId=799');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(TestBed.inject(Router).url).toBe('/pages/stu/stu_abc?nids=999&readonly=1');
- expect(harness.routeNativeElement?.querySelector('.selection-header')?.textContent).toContain('词库学习进度');
- await harness.navigateByUrl('/pages/stu/stu_calendar');
- const calendarComponent=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- calendarComponent.memoryMonth.set(new Date(2026,7,1));
- calendarComponent.memorySelectedDate.set('2026-08-02');
- (calendarComponent as any).loadCalendar();
- harness.fixture.detectChanges();
- expect(harness.fixture.nativeElement.querySelector('.tabbar')).toBeNull();
- expect(harness.routeNativeElement?.querySelector('.memory-student-filter')).toBeNull();
- expect(harness.routeNativeElement?.querySelectorAll('.memory-date').length).toBe(42);
- expect(harness.routeNativeElement?.querySelectorAll('.memory-date.completed, .memory-date.due').length).toBe(2);
- expect(harness.routeNativeElement?.querySelector('.memory-overview')?.textContent).toContain('2 / 3');
- expect(harness.routeNativeElement?.querySelector('.memory-date-tasks')?.textContent).toContain('高中英语复习');
- expect(harness.routeNativeElement?.querySelector('.review-sequence')?.textContent).toContain('第 3 次复习');
- expect(harness.routeNativeElement?.querySelector('.first-learned-at')?.textContent).toContain('首次学习:2026-07-20 10:20');
- for (let index = 0; index < 3; index += 1) {
- (harness.routeNativeElement?.querySelector('[aria-label="上个月"]') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- }
- expect(harness.routeNativeElement?.querySelector('[aria-label^="2026-05-15"]')?.classList).toContain('completed');
- expect(harness.routeNativeElement?.textContent).toContain('张雅茜');
- expect(harness.routeNativeElement?.querySelector('.memory-overview header b')?.textContent).toContain('67%');
- expect(harness.routeNativeElement?.querySelector('.memory-stats')?.textContent).toContain('2 / 3');
- await harness.navigateByUrl('/pages/home/ucenter');
- expect(harness.fixture.nativeElement.querySelector('.tabbar')).not.toBeNull();
- expect(harness.routeNativeElement?.querySelector('.new-word-entry')?.getAttribute('href')).toBe('/pages/home/cart');
- expect(harness.routeNativeElement?.querySelector('.course-memory')?.textContent).toContain('21 天抗遗忘计划');
- expect(harness.routeNativeElement?.querySelector('.memory-overview em')?.textContent).toContain('67%');
- expect(harness.routeNativeElement?.querySelector('.memory-overview')?.textContent).toContain('覆盖 3 个复习日');
- expect(harness.routeNativeElement?.querySelector('.memory-counts')?.textContent).toContain('3总任务');
- expect(harness.routeNativeElement?.querySelector('.memory-counts')?.textContent).toContain('2已完成');
- expect(harness.routeNativeElement?.querySelector('.memory-counts')?.textContent).toContain('1到期待复习');
- expect(harness.routeNativeElement?.querySelector('.memory-counts')?.textContent).toContain('0未来待复习');
- await harness.navigateByUrl('/pages/stu/record?id=827482&gid=828268&kcid=203');
- const recordWord = harness.routeNativeElement?.querySelector('.record-word') as HTMLButtonElement;
- expect(recordWord.querySelector('.record-copy strong')?.textContent).toBe('apple');
- expect(harness.routeNativeElement?.textContent).not.toContain('苹果');
- recordWord.click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(recordWord.querySelector('.record-copy strong')?.textContent).toBe('苹果');
- expect(harness.routeNativeElement?.querySelector('.record-overview')?.textContent).toContain('1 / 1');
- await harness.navigateByUrl('/pages/member/starshop');
- expect(harness.fixture.nativeElement.querySelector('.tabbar')).toBeNull();
- expect(harness.routeNativeElement?.querySelector('.word-select-list strong')?.textContent).toBe('tend');
- expect(harness.routeNativeElement?.querySelector('.word-select-list')?.textContent).not.toContain('@张雅茜');
- (harness.routeNativeElement?.querySelector('.word-select-list > button') as HTMLButtonElement).click();
- (harness.routeNativeElement?.querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- const selectedNewWords = JSON.parse(sessionStorage.getItem('xiaoshu.learning.100.100.practice.selectedWords') ?? '[]') as Array<{ word?: string }>;
- expect(selectedNewWords[0]?.word).toBe('tend');
- expect(sessionStorage.getItem('xiaoshu.learning.100.100.practice.selectedWords')).not.toContain('@张雅茜');
- await harness.navigateByUrl('/pages/his/well?nid=3');
- expect(harness.fixture.nativeElement.querySelector('.tabbar')).toBeNull();
- expect(harness.routeNativeElement?.textContent).toContain('阅读理解专项');
- await harness.navigateByUrl('/pages/home/cart');
- expect(harness.fixture.nativeElement.querySelector('.tabbar')).not.toBeNull();
- expect(harness.fixture.nativeElement.querySelector('.app-header .icon-button')).toBeNull();
- expect(harness.fixture.nativeElement.querySelector('.app-header h1')?.textContent).toContain('伴学中心');
- expect(harness.routeNativeElement?.querySelector('.library-entry')).toBeNull();
- expect(harness.routeNativeElement?.textContent).toContain('我的学习内容');
- expect(harness.routeNativeElement?.querySelectorAll('.course-list li').length).toBe(2);
- expect(harness.routeNativeElement?.querySelectorAll('.course-list button').length).toBe(2);
- expect((harness.routeNativeElement?.querySelector('.course-list button') as HTMLButtonElement).disabled).toBeFalse();
- expect((harness.routeNativeElement?.querySelectorAll('.course-list button')[1] as HTMLButtonElement).disabled).toBeFalse();
- expect(harness.routeNativeElement?.textContent).toContain('【七年级上册】同步词汇');
- expect(harness.routeNativeElement?.textContent).toContain('点击查看老师分配的单词列表');
- (harness.routeNativeElement?.querySelector('.course-list button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(TestBed.inject(Router).url).toBe('/pages/stu/stu_list?nid=801&bindingId=701');
- expect(harness.routeNativeElement?.querySelectorAll('.node-list button').length).toBe(2);
- expect((TestBed.inject(ApiService) as unknown as LearningModulesApiService).lastNodeParams['bindingId']).toBe('701');
- await harness.navigateByUrl('/pages/home/cart');
- expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(0);
- expect(harness.routeNativeElement?.querySelectorAll('.calendar-day').length).toBe(42);
- const allDates = Array.from(harness.routeNativeElement?.querySelectorAll('.range-tabs button') ?? [])
- .find((button) => button.textContent?.trim() === '全部') as HTMLButtonElement;
- allDates.click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(3);
- expect(harness.routeNativeElement?.textContent).toContain('同步伴学');
- expect(harness.routeNativeElement?.textContent).toContain('历史伴学');
- const plannedIncompleteFilter = Array.from(harness.routeNativeElement?.querySelectorAll('.schedule-filters button') ?? [])
- .find((button) => button.textContent?.includes('计划未完成')) as HTMLButtonElement;
- expect(plannedIncompleteFilter.textContent).toContain('1');
- plannedIncompleteFilter.click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(1);
- expect(harness.routeNativeElement?.textContent).toContain('计划未完成');
- expect(harness.routeNativeElement?.textContent).not.toContain('未来计划');
- (harness.routeNativeElement?.querySelector('.schedule-filters button') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- expect(api.lastScheduleParams['mode']).toBe('student');
- expect(api.lastScheduleParams['pageSize']).toBe(20);
- const finishedFilter = Array.from(harness.routeNativeElement?.querySelectorAll('.schedule-filters button') ?? [])
- .find((button) => button.textContent?.includes('已结束')) as HTMLButtonElement;
- finishedFilter.click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(1);
- expect(harness.routeNativeElement?.textContent).toContain('历史伴学');
- const allFilter = harness.routeNativeElement?.querySelector('.schedule-filters button') as HTMLButtonElement;
- allFilter.click();
- harness.fixture.detectChanges();
- const upcomingSchedule = Array.from(harness.routeNativeElement?.querySelectorAll('.schedule-list article') ?? [])
- .find((article) => article.textContent?.includes('同步伴学')) as HTMLElement;
- upcomingSchedule.click();
- await harness.fixture.whenStable();
- expect(TestBed.inject(Router).url).toBe('/pages/shop/stu_get_order?id=901');
- await harness.navigateByUrl('/pages/his/his');
- expect(harness.fixture.nativeElement.querySelector('.tabbar')).toBeNull();
- const aiReadingFeature = harness.routeNativeElement?.querySelector('.ai-reading-feature') as HTMLElement;
- expect(aiReadingFeature.textContent).toContain('AI 阅读巩固');
- expect(aiReadingFeature.textContent).toContain('生成阅读');
- expect(aiReadingFeature.textContent).toContain('AI 批改');
- expect(aiReadingFeature.querySelector('img')?.getAttribute('src')).toBe('/static/images/ai-reading-journey.png');
- const aiReadingCta = aiReadingFeature.querySelector('.ai-reading-cta') as HTMLButtonElement;
- expect(aiReadingCta.disabled).toBeFalse();
- expect(aiReadingFeature.textContent).toContain('最近学过的 1 个单词');
- expect(aiReadingCta.textContent).toContain('立即生成阅读');
- aiReadingCta.click();
- await harness.fixture.whenStable();
- const aiReadingRouter = TestBed.inject(Router);
- expect(aiReadingRouter.url).toContain('/words/go-reading');
- expect(aiReadingRouter.parseUrl(aiReadingRouter.url).queryParams['returnUrl']).toBe('/pages/his/his');
- expect(aiReadingRouter.parseUrl(aiReadingRouter.url).queryParams['GeneralID']).toBe('201');
- await harness.navigateByUrl('/pages/his/his');
- const currentLearningCard = harness.routeNativeElement?.querySelector('.current-learning-card') as HTMLElement;
- const learningRecordCard = harness.routeNativeElement?.querySelector('.learning-record-card') as HTMLElement;
- expect(currentLearningCard.textContent).toContain('我的学习内容');
- const records = harness.fixture.debugElement.query(By.directive(StudyRecordsPageComponent)).componentInstance as StudyRecordsPageComponent;
- expect(records.courseTitle({ Title: '单词课|高中@人教版2022年录', Title2: '人教版2022年录' })).toBe('【高中】人教版2022年录');
- expect(records.courseTitle({ Title: '单词课|初中@人教版2024年9月录', Title2: '人教版2024年9月录' })).toBe('【初中】人教版2024年9月录');
- expect(currentLearningCard.querySelectorAll('.current-learning-list button').length).toBe(2);
- expect((currentLearningCard.querySelectorAll('.current-learning-list button')[1] as HTMLButtonElement).disabled).toBeFalse();
- expect(currentLearningCard.compareDocumentPosition(learningRecordCard) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
- (currentLearningCard.querySelector('.current-learning-list button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(TestBed.inject(Router).url).toBe('/pages/stu/stu_list?nid=801&bindingId=701');
- expect(harness.routeNativeElement?.querySelectorAll('.node-list button').length).toBe(2);
- await harness.navigateByUrl('/pages/his/his');
- expect(harness.routeNativeElement?.textContent).toContain('初中英语 / Unit 1');
- expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(2);
- (harness.routeNativeElement?.querySelector('.learning-record-card .learning-item') as HTMLElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(TestBed.inject(Router).url).toBe('/pages/his/his_words?id=201');
- expect(harness.routeNativeElement?.querySelector('.readonly-word-header')?.textContent).toContain('学生只读');
- expect(harness.routeNativeElement?.querySelector('.readonly-word-card')).not.toBeNull();
- expect(harness.routeNativeElement?.querySelector('.selection-header')).toBeNull();
- await harness.navigateByUrl('/pages/his/his');
- (harness.routeNativeElement?.querySelector('.date-trigger') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- const currentMonth = new Date();
- const monthDifference = (2026 - currentMonth.getFullYear()) * 12 + (7 - currentMonth.getMonth());
- const shiftLabel = monthDifference < 0 ? '上个月' : '下个月';
- for (let index = 0; index < Math.abs(monthDifference); index += 1) {
- (harness.routeNativeElement?.querySelector(`[aria-label="${shiftLabel}"]`) as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- }
- expect(harness.routeNativeElement?.querySelector('.date-picker-popover header strong')?.textContent).toContain('2026年8月');
- expect(harness.routeNativeElement?.querySelectorAll('.date-picker-day').length).toBe(42);
- expect(harness.routeNativeElement?.querySelectorAll('.date-picker-day.has-record').length).toBe(2);
- expect(harness.routeNativeElement?.querySelector('.date-picker-day.has-record')?.getAttribute('aria-label')).toContain('2026-08-01');
- (harness.routeNativeElement?.querySelector('[aria-label^="2026-08-01"]') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(1);
- expect(harness.routeNativeElement?.querySelector('.learning-record-card')?.textContent).not.toContain('高中英语 / Unit 2');
- (harness.routeNativeElement?.querySelector('.record-actions button') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(2);
- const completedReading = harness.routeNativeElement?.querySelector('.reading-button.completed') as HTMLButtonElement;
- expect(completedReading.textContent).toContain('已完成阅读');
- expect(completedReading.getAttribute('aria-label')).toBe('查看已完成的历史阅读理解');
- completedReading.click();
- await harness.fixture.whenStable();
- const router = TestBed.inject(Router);
- expect(router.url).toContain('/words/reading');
- expect(router.parseUrl(router.url).queryParams['sid']).toBe('readingarticle201');
- expect(router.parseUrl(router.url).queryParams['returnUrl']).toBe('/pages/his/his');
- await harness.navigateByUrl('/pages/his/his');
- const newReading = harness.routeNativeElement?.querySelector('.reading-button:not(.completed)') as HTMLButtonElement;
- expect(newReading.textContent).toContain('阅读');
- newReading.click();
- await harness.fixture.whenStable();
- expect(router.url).toContain('/words/go-reading');
- expect(router.parseUrl(router.url).queryParams['returnUrl']).toBe('/pages/his/his');
- expect(harness.routeNativeElement?.querySelector('.back-button')).not.toBeNull();
- (harness.routeNativeElement?.querySelector('.back-button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- expect(router.url).toBe('/pages/his/his');
- (harness.fixture.nativeElement.querySelector('.app-header .icon-button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- expect(router.url).toBe('/pages/home/index');
- await harness.navigateByUrl('/pages/his/exam');
- expect(harness.routeNativeElement?.textContent).toContain('第一组问题');
- expect(harness.routeNativeElement?.textContent).toContain('相当于初二水平');
- expect(harness.routeNativeElement?.textContent).toContain('共 1 题');
- const startButton = harness.routeNativeElement?.querySelector('.exam-intro > button') as HTMLButtonElement;
- startButton.click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.question-word')?.textContent).toContain('apple');
- expect(harness.routeNativeElement?.querySelector('.question-card > h2')).toBeNull();
- expect(harness.routeNativeElement?.querySelectorAll('.exam-options button').length).toBe(1);
- (harness.routeNativeElement?.querySelector('.exam-options button') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- });
- it('matches coach review tasks to student names by ID when task name fields are blank', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const response = new Subject<ApiEnvelope<unknown>>();
- api.reviewPageResponse = response;
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/home/index');
- response.next({ retcode: 1, result: {
- items: [
- { GeneralID: 102, yhid: 100, honeyName: '', Title: '旧姓名@复习', kywsj: String(api.lastMemoryParams['date']), fxzt: 0, xxjlid: 900 },
- { GeneralID: 103, yhid: '101', honeyName: ' ', HoneyName: '', kywsj: String(api.lastMemoryParams['date']), fxzt: 0, xxjlid: 901 },
- ],
- students: [{ id: '101', name: '李同学', taskCount: 1 }, { id: '100', name: '张雅茜', taskCount: 1 }],
- page: { itemCount: 2, pageCount: 1 },
- summary: { total: 2, completed: 0, due: 2, today: 0, income: 0 }, dates: [],
- } });
- response.complete();
- api.reviewPageResponse = null;
- harness.fixture.detectChanges();
- const names = Array.from(harness.routeNativeElement?.querySelectorAll('.coach-memory-copy strong') ?? []).map((node) => node.textContent);
- expect(names).toEqual(['张雅茜', '李同学']);
- const home = harness.fixture.debugElement.query(By.directive(HomePageComponent)).componentInstance as HomePageComponent;
- expect(home.coachReviewStudent({ yhid: 102, honeyName: '', HoneyName: ' ', Title: '王同学@复习' })).toBe('王同学');
- expect(home.coachReviewStudent({ yhid: 103, honeyName: '', Title: ' ' })).toBe('学员 103');
- expect(home.coachReviewStudent({ honeyName: '' })).toBe('未关联学员');
- (harness.routeNativeElement?.querySelectorAll('.coach-memory-list article > button')[1] as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- expect(session.student()).toEqual(jasmine.objectContaining({ userId: 101, honeyName: '李同学' }));
- expect(TestBed.inject(Router).url).toContain('/pages/stu/record?id=901&gid=103');
- });
- it('keeps the complete point-reading flow available to coaches', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/home/index');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const coachLinks = Array.from(harness.routeNativeElement?.querySelectorAll('.coach-quick-grid > a') ?? []).map((link) => link.getAttribute('href'));
- expect(coachLinks).toEqual(['/pages/home/shop', '/pages/member/ke_xiao', '/pages/his/his', '/pages/member/ke_fuxi']);
- expect(harness.routeNativeElement?.querySelector('.home-header .header-action')).toBeNull();
- const coachAccountTab = (Array.from(harness.fixture.nativeElement.querySelectorAll('.tabbar a')) as HTMLAnchorElement[])
- .find((link) => link.getAttribute('href') === '/pages/home/ucenter');
- expect(coachAccountTab?.textContent).toContain('我的');
- expect(harness.routeNativeElement?.querySelector('.content-section')).toBeNull();
- const memoryApi = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- expect(memoryApi.lastMemoryParams).toEqual(jasmine.objectContaining({ uid: 300, pageSize:100, scope:'today', includeMetadata:false, includeIncome:false }));
- expect(harness.routeNativeElement?.querySelector('.coach-memory-board')?.textContent).toContain('抗遗忘带练');
- expect(harness.routeNativeElement?.querySelector('.coach-memory-board')?.textContent).toContain('张雅茜');
- expect(harness.routeNativeElement?.querySelector('.coach-memory-list article.ready > button')?.textContent).toContain('查看计划');
- expect(harness.routeNativeElement?.querySelector('.coach-memory-footer')?.getAttribute('href')).toBe('/pages/stu/stu_calendar');
- (harness.routeNativeElement?.querySelector('.coach-memory-list article.ready > button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- expect(TestBed.inject(Router).url).toContain('/pages/stu/record?id=900&gid=102');
- expect(session.student()?.userId).toBe(100);
- await harness.navigateByUrl('/pages/stu/stu_calendar');
- const calendarComponent=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- calendarComponent.memoryMonth.set(new Date(2026,7,1));
- calendarComponent.memorySelectedDate.set('2026-08-02');
- (calendarComponent as any).loadCalendar();
- harness.fixture.detectChanges();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(memoryApi.lastMemoryParams).toEqual(jasmine.objectContaining({ uid: 300, pageSize:20 }));
- expect(harness.routeNativeElement?.querySelector('.memory-copy')?.textContent).toContain('关联学员抗遗忘任务');
- expect(harness.routeNativeElement?.querySelector('.memory-date-tasks')?.textContent).toContain('张雅茜');
- expect(harness.routeNativeElement?.querySelector('.memory-date-tasks button')?.textContent).toContain('带学生复习');
- const memoryStudentFilter = harness.routeNativeElement?.querySelector('[aria-label="筛选抗遗忘学员"] select') as HTMLSelectElement;
- expect(memoryStudentFilter.options.length).toBe(2);
- memoryStudentFilter.value = '100';
- memoryStudentFilter.dispatchEvent(new Event('change'));
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.memory-date-tasks')?.textContent).toContain('张雅茜');
- expect(harness.routeNativeElement?.querySelector('.memory-date-tasks')?.textContent).not.toContain('李同学');
- expect(harness.routeNativeElement?.querySelector('.memory-stats')?.textContent).toContain('2 / 3');
- await harness.navigateByUrl('/pages/member/ke_xiao');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const monthFilter = harness.routeNativeElement?.querySelector('[aria-label="按月份筛选销课记录"]') as HTMLSelectElement;
- const monthPicker = harness.routeNativeElement?.querySelector('.month-control .xs-dropdown-trigger') as HTMLButtonElement;
- expect(monthFilter.value).toBe('all');
- expect(monthFilter.options.length).toBe(4);
- expect(monthPicker).not.toBeNull();
- expect(Number.parseFloat(getComputedStyle(monthPicker).paddingLeft)).toBeGreaterThanOrEqual(40);
- expect(monthPicker.getBoundingClientRect().height).toBe(46);
- expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(5);
- monthFilter.value = '2026-03';
- monthFilter.dispatchEvent(new Event('change'));
- const studentSearch = harness.routeNativeElement?.querySelector('[aria-label="按学生姓名筛选销课记录"]') as HTMLInputElement;
- studentSearch.value = '花';
- studentSearch.dispatchEvent(new Event('input'));
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(1);
- expect(harness.routeNativeElement?.querySelector('.schedule-list')?.textContent).toContain('花花');
- expect(harness.routeNativeElement?.querySelector('.schedule-band > header')?.textContent).toContain('1 / 5');
- (harness.routeNativeElement?.querySelector('.history-filter-panel footer button') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(5);
- await harness.navigateByUrl('/pages/his/his');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect((harness.routeNativeElement?.querySelector('.student-filter select') as HTMLSelectElement).selectedOptions[0]?.textContent).toContain('张雅茜');
- expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(2);
- expect(session.student()?.userId).toBe(100);
- (harness.routeNativeElement?.querySelector('.learning-record-card .learning-item') as HTMLElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(TestBed.inject(Router).url).toBe('/pages/his/his_words?id=201');
- expect(harness.routeNativeElement?.querySelector('.readonly-word-header')?.textContent).toContain('历史记录');
- expect(harness.routeNativeElement?.querySelector('.readonly-word-card')?.textContent).toContain('apple');
- expect(harness.routeNativeElement?.querySelector('.readonly-word-card')?.textContent).toContain('共 1 个单词');
- expect(harness.routeNativeElement?.querySelector('.selection-header')).toBeNull();
- await harness.navigateByUrl('/pages/his/his');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const teacherCourse = harness.routeNativeElement?.querySelector('.current-learning-list button') as HTMLButtonElement;
- expect(teacherCourse.disabled).toBeFalse();
- expect(teacherCourse.classList.contains('readonly')).toBeFalse();
- expect(teacherCourse.textContent).toContain('选择本次学习单元');
- teacherCourse.click();
- await harness.fixture.whenStable();
- expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_list');
- await harness.navigateByUrl('/pages/home/ucenter');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const teacherServices = Array.from(harness.routeNativeElement?.querySelectorAll('.service-grid > a') ?? []).map((link) => link.getAttribute('href'));
- expect(teacherServices).toEqual(['/pages/home/shop', '/pages/member/ke_xiao', '/pages/his/his', '/pages/member/feedback']);
- expect(harness.routeNativeElement?.querySelector('.coach-wallet-strip')?.textContent).toContain('累计复习工资');
- await harness.navigateByUrl('/pages/stu/stu_list?nid=801&bindingId=701');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect((TestBed.inject(ApiService) as unknown as LearningModulesApiService).lastNodeParams['userId']).toBe(100);
- const units = harness.routeNativeElement?.querySelectorAll('.node-list button') as NodeListOf<HTMLButtonElement>;
- units[0].click();
- units[1].click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.unit-selection-summary')?.textContent).toContain('已选 2 个单元');
- (harness.routeNativeElement?.querySelector('.unit-actions .primary-button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const router = TestBed.inject(Router);
- expect(router.url).toContain('/pages/stu/stu_abc');
- expect(harness.routeNativeElement?.querySelector('.pending-column')?.textContent).toContain('banana');
- expect(harness.routeNativeElement?.querySelector('.completed-column')).toBeNull();
- expect(harness.routeNativeElement?.querySelectorAll('.pending-column .word-refine-item').length).toBe(1);
- (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.completed-column')?.textContent).toContain('apple');
- expect(harness.routeNativeElement?.querySelector('.pending-column')).toBeNull();
- (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[0] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- const firstWord = harness.routeNativeElement?.querySelector('.pending-column .word-refine-item') as HTMLElement;
- (firstWord.querySelector('.word-reveal') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- (firstWord.querySelector('.known-button') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.pending-column .word-refine-item').length).toBe(0);
- expect(harness.routeNativeElement?.querySelector('.selection-header .primary-button')?.textContent).toContain('保存识词结果');
- (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.completed-column .word-refine-item').length).toBe(2);
- (harness.routeNativeElement?.querySelector('.completed-word-action button') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.completed-column .word-refine-item').length).toBe(1);
- (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[0] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.pending-column .word-refine-item').length).toBe(1);
- (harness.routeNativeElement?.querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/stu_con');
- expect(harness.routeNativeElement?.querySelectorAll('.repeat-list > button').length).toBe(1);
- expect(harness.routeNativeElement?.querySelector('.readonly-word-header')).toBeNull();
- await harness.navigateByUrl('/pages/stu/pl_stu5?nids=811&pnid=801&bindingId=701');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const spellingActions = harness.routeNativeElement?.querySelector('.teacher-spelling-actions') as HTMLElement;
- expect(spellingActions.querySelectorAll('button').length).toBe(3);
- expect(spellingActions.textContent).toContain('跳到下一关');
- expect((harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent).words().length).toBe(1);
- expect(localStorage.getItem('xiaoshu.learning.300.100.701._page_word_orilist')).not.toBeNull();
- (spellingActions.querySelectorAll('button')[1] as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toBe('/pages/his/his');
- const standaloneRecord = (TestBed.inject(ApiService) as unknown as LearningModulesApiService).lastStandaloneLearningRecord;
- expect(JSON.parse(String(standaloneRecord['content']))).toEqual(jasmine.objectContaining({ ModelID: 56, Hits: 1, title: '张雅茜' }));
- expect(JSON.parse(String(standaloneRecord['addon']))).toEqual(jasmine.objectContaining({ UserID: 100, pl: 300, learned: 1, createReviewPlan: false }));
- }, 20000);
- it('loads appointment courses and units for the appointment student when no student is selected in the session', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- session.student.set(null);
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/shop/get_order?id=901');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- expect(session.student()?.userId).toBe(100);
- expect(api.lastAppointmentCourseParams['orderId']).toBe('901');
- expect(api.lastNodeParams['userId']).toBe(100);
- const courseSelect = harness.routeNativeElement?.querySelector('.course-section select') as HTMLSelectElement;
- expect(courseSelect).not.toBeNull();
- expect(courseSelect.options.length).toBeGreaterThanOrEqual(2);
- expect(courseSelect.closest('.course-section')?.textContent).toContain('七年级上册');
- expect(harness.routeNativeElement?.querySelectorAll('.unit-grid article').length).toBe(2);
- const unitButtons = harness.routeNativeElement?.querySelectorAll<HTMLButtonElement>('.unit-select');
- expect(unitButtons?.[0].textContent).toContain('已学 5%');
- expect(unitButtons?.[0].textContent).toContain('1/20 词');
- expect(unitButtons?.[1].textContent).toContain('已学 0%');
- expect(unitButtons?.[1].textContent).toContain('0/18 词');
- expect((unitButtons?.[0].querySelector('.unit-progress-track > span') as HTMLElement).style.width).toBe('5%');
- unitButtons?.[0].click();
- unitButtons?.[1].click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.unit-select[aria-pressed="true"]').length).toBe(2);
- expect(unitButtons?.[0].textContent).toContain('已学 5%');
- });
- it('distinguishes completed, empty and unavailable appointment vocabulary progress', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- api.unitRows = [
- { NodeID: 811, NodeName: '已学全册', yx_word: '20', total: '20' },
- { NodeID: 812, NodeName: '空册', yx_word: 0, total: 0 },
- { NodeID: 813, NodeName: '缺少统计' },
- { NodeID: 814, NodeName: '异常统计', yx_word: 'invalid', total: 20 },
- ];
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/shop/get_order?id=901');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const units = harness.routeNativeElement?.querySelectorAll('.unit-select');
- expect(units?.[0].textContent).toContain('已学 100%');
- expect(units?.[0].textContent).toContain('20/20 词');
- expect(units?.[1].textContent).toContain('已学 0%');
- expect(units?.[1].textContent).toContain('暂无单词');
- for (const index of [2, 3]) {
- expect(units?.[index].textContent).toContain('暂无进度数据');
- expect(units?.[index].querySelector('.unit-progress-track')).toBeNull();
- }
- });
- it('ends without requiring feedback and displays the server-confirmed lesson pay', async () => {
- user.set({userId:300,userName:'coach',honeyName:'张老师',groupId:3});session.groupId.set(3);
- const api=TestBed.inject(ApiService) as unknown as LearningModulesApiService;api.appointmentStatus=10;
- spyOn(TestBed.inject(PlatformService),'confirm').and.resolveTo(true);
- const harness=await RouterTestingHarness.create();await harness.navigateByUrl('/pages/shop/get_order?id=901');await harness.fixture.whenStable();harness.fixture.detectChanges();
- const component=harness.fixture.debugElement.query(By.directive(AppointmentPageComponent)).componentInstance as AppointmentPageComponent;
- await component.endLesson();expect(api.completionRequests.length).toBe(1);expect(api.completionRequests[0]['feedback']).toBeUndefined();
- api.appointmentStatus=30;api.completionResponse.next({retcode:0,result:{status:30,teacherPay:45,payStatus:'earned',feedbackStatus:'pending'}});api.completionResponse.complete();
- harness.fixture.detectChanges();expect(harness.routeNativeElement?.textContent).toContain('本节带课工资 ¥45.00');expect(harness.routeNativeElement?.textContent).toContain('反馈待补');
- });
- it('retains the optional feedback-and-complete dialog and submits once after validation', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- api.appointmentStatus = 10;
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/shop/get_order?id=901');
- const component = harness.fixture.debugElement.query(By.directive(AppointmentPageComponent)).componentInstance as AppointmentPageComponent;
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const dialog = harness.routeNativeElement?.querySelector('dialog') as HTMLDialogElement;
- const endButton = harness.routeNativeElement?.querySelector('.appointment-actions .primary-button') as HTMLButtonElement;
- expect(dialog.open).toBeFalse();
- component.openCompletionFeedback();
- harness.fixture.detectChanges();
- expect(dialog.open).toBeTrue();
- expect(api.completionRequests.length).toBe(0);
- const submit = dialog.querySelector('.feedback-actions .primary-button') as HTMLButtonElement;
- submit.click();
- harness.fixture.detectChanges();
- expect(dialog.querySelector('[role="alert"]')?.textContent).toContain('请填写本次学习内容');
- expect(api.completionRequests.length).toBe(0);
- const summary = dialog.querySelector('textarea') as HTMLTextAreaElement;
- summary.value = 'Unit 3 词汇';
- summary.dispatchEvent(new Event('input'));
- await harness.fixture.whenStable();
- (dialog.querySelector('.feedback-actions .secondary-button') as HTMLButtonElement).click();
- expect(dialog.open).toBeFalse();
- expect(api.appointmentStatus).toBe(10);
- component.openCompletionFeedback();
- harness.fixture.detectChanges();
- expect((dialog.querySelector('textarea') as HTMLTextAreaElement).value).toBe('Unit 3 词汇');
- component.reviewStatus = '完成';
- component.trainingStatus = '需要巩固';
- component.trainingSummary = '下次复习 Unit 3';
- component.noHomework = true;
- submit.click();
- submit.click();
- harness.fixture.detectChanges();
- expect(api.completionRequests.length).toBe(1);
- expect(JSON.parse(String(api.completionRequests[0]['feedback']))).toEqual(jasmine.objectContaining({ contentSummary: 'Unit 3 词汇', noHomework: true, homework: '无作业' }));
- expect(submit.disabled).toBeTrue();
- dialog.dispatchEvent(new Event('cancel', { cancelable: true }));
- expect(dialog.open).toBeTrue();
- api.appointmentStatus = 30;
- api.completionResponse.next({ retcode: 1, result: {} });
- api.completionResponse.complete();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('dialog')).toBeNull();
- expect(harness.routeNativeElement?.textContent).toContain('已结课');
- });
- it('keeps feedback editable after a failed submission and allows closing with Escape', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- api.appointmentStatus = 10;
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/shop/get_order?id=901');
- const component = harness.fixture.debugElement.query(By.directive(AppointmentPageComponent)).componentInstance as AppointmentPageComponent;
- await harness.fixture.whenStable();
- component.openCompletionFeedback();
- component.contentSummary = 'Unit 3';
- component.reviewStatus = '完成';
- component.trainingStatus = '正常进行';
- component.trainingSummary = '继续 Unit 4';
- component.noHomework = true;
- component.finishCoachLesson();
- api.completionResponse.error(new Error('提交失败,请重试'));
- harness.fixture.detectChanges();
- const dialog = harness.routeNativeElement?.querySelector('dialog') as HTMLDialogElement;
- expect(dialog.open).toBeTrue();
- expect(dialog.querySelector('[role="alert"]')?.textContent).toContain('提交失败,请重试');
- expect((dialog.querySelector('fieldset') as HTMLFieldSetElement).disabled).toBeFalse();
- expect(component.contentSummary).toBe('Unit 3');
- expect(api.appointmentStatus).toBe(10);
- dialog.dispatchEvent(new Event('cancel', { cancelable: true }));
- expect(dialog.open).toBeFalse();
- });
- it('counts words marked as known as completed and persists them for the student', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- session.student.set({ userId: 100, userName: 'student', honeyName: '张雅茜', groupId: 1 });
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/stu/stu_abc?nids=811,812&pnid=801');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const pendingWord = harness.routeNativeElement?.querySelector('.pending-column .word-refine-item') as HTMLElement;
- (pendingWord.querySelector('.word-reveal') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- (pendingWord.querySelector('.known-button') as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- (harness.routeNativeElement?.querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- expect(api.lastLearningWordUpdate).toEqual(jasmine.objectContaining({ uid: 100, wordsId: '1002', kcid: '801', save: 1 }));
- expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_abc');
- expect(harness.routeNativeElement?.querySelector('.completed-column')).toBeNull();
- (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.completed-column .word-refine-item').length).toBe(2);
- expect(harness.routeNativeElement?.querySelector('.pending-column')).toBeNull();
- });
- it('confirms three rounds into 17 words and can continue selecting before ending the lesson', async () => {
- user.set({userId:300,groupId:3}); session.groupId.set(3);session.student.set({userId:100,groupId:1});
- const api=TestBed.inject(ApiService) as unknown as LearningModulesApiService;api.appointmentStatus=10;
- api.studyBatches=[9,5,3].map((count,index)=>({batchId:'round-'+index,version:1,status:'draft',bindingId:'binding-801',words:Array.from({length:count},(_,i)=>({GeneralID:index*100+i+1,Title:'word'+index+'-'+i,check:0}))}));
- const harness=await RouterTestingHarness.create();
- for(let index=0;index<3;index++){
- await harness.navigateByUrl('/pages/stu/pl_end?orderId=901&bindingId=binding-801&batchId=round-'+index);await harness.fixture.whenStable();harness.fixture.detectChanges();
- const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- expect(component.words().length).toBe([9,5,3][index]);component.markAllKnown();component.submitReview(index<2);await harness.fixture.whenStable();harness.fixture.detectChanges();
- expect(TestBed.inject(Router).url).toBe('/pages/shop/get_order?id=901'+(index===2?'&feedback=1':''));
- expect(harness.routeNativeElement?.textContent).toContain('本节学习成果 · '+[9,14,17][index]+' 个词');
- }
- expect(api.completionRequests.length).toBe(0);
- });
- it('keeps round choices on save failure and retries with the same command key', async () => {
- user.set({userId:300,groupId:3});session.groupId.set(3);session.student.set({userId:100,groupId:1});
- const api=TestBed.inject(ApiService) as unknown as LearningModulesApiService;api.appointmentStatus=10;
- api.studyBatches=[{batchId:'retry-round',version:1,status:'draft',bindingId:'binding-801',courseId:'802',words:[{GeneralID:1001,Title:'apple',check:0}]}];
- const post=api.post.bind(api);let fail=true;const spy=spyOn(api,'post').and.callFake((action,params)=>action==='stu_record_update_v2'&&fail?(fail=false,throwError(()=>new Error('断网'))):post(action,params));
- const harness=await RouterTestingHarness.create();await harness.navigateByUrl('/pages/stu/pl_end?orderId=901&bindingId=binding-801&batchId=retry-round');await harness.fixture.whenStable();harness.fixture.detectChanges();
- const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;component.markAllKnown();component.submitReview(true);await harness.fixture.whenStable();
- expect(component.words().length).toBe(1);expect(component.reviewCount(1)).toBe(1);expect(TestBed.inject(Router).url).toContain('/pl_end');
- component.submitReview(true);await harness.fixture.whenStable();const requests=spy.calls.allArgs().filter(([action])=>action==='stu_record_update_v2');expect(requests.length).toBe(2);expect(requests[0][1]?.['requestKey']).toBe(requests[1][1]?.['requestKey']);
- expect(api.lastLearningWordUpdate['kcid']).toBe('802'); // Resume uses the batch book, not the scheduled book.
- });
- it('finishes the last vocabulary group, loads the coach record and opens completion feedback', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- session.student.set({ userId: 100, honeyName: '张雅茜', groupId: 1 });
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- api.appointmentStatus = 10;
- const word = { GeneralID: 1001, NodeID: 811, Title: 'apple', sy: '苹果' };
- localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_word_orilist', JSON.stringify([[word]]));
- localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_current_learn', '1');
- // Stale page-count metadata must not create a nonexistent next group.
- localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_total_page', '2');
- localStorage.removeItem('xiaoshu.learning.300.100.901.unbound.learn_mode');
- const harness = await RouterTestingHarness.create();
- const router = TestBed.inject(Router);
- const navigate = spyOn(router, 'navigate').and.callThrough();
- await harness.navigateByUrl('/pages/stu/stu_con?nids=811&pnid=801&orderId=901');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const learning = () => harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- learning().skipStudyList();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/stu3');
- const pair = learning().words()[0];
- learning().chooseMatch('left', pair);
- learning().chooseMatch('right', pair);
- learning().continueAfterStage();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/stu4');
- learning().chooseMeaning(learning().words()[0]);
- learning().continueAfterStage();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/pl_stu5');
- learning().skipSpellingStage();
- expect(learning().hasNextWordBatch).toBeFalse();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/pl_end');
- expect(api.lastStudyQuery['orderId']).toBe('901');
- expect(harness.routeNativeElement?.querySelector('.empty-state.error')).toBeNull();
- expect(learning().words()[0].word).toBe('apple');
- learning().markAllKnown();
- learning().submitReview();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- harness.fixture.detectChanges();
- expect(router.url).toBe('/pages/shop/get_order?id=901&feedback=1');
- expect((harness.routeNativeElement?.querySelector('dialog') as HTMLDialogElement).open).toBeTrue();
- expect(api.appointmentStatus).toBe(10);
- expect(api.completionRequests.length).toBe(0);
- expect(api.studyUpdates.length).toBe(2);
- expect(JSON.parse(String(api.studyUpdates[1]['addon'])).xxqs[0].check).toBe(1);
- expect(navigate.calls.all().every(call => call.args[1]?.replaceUrl === true)).toBeTrue();
- }, 20000);
- it('advances only to a real next group and returns from the last stage to its course in one click', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- session.student.set({ userId: 100, honeyName: '张雅茜', groupId: 1 });
- const pages = [[{ GeneralID: 1001, Title: 'apple', sy: '苹果' }, { GeneralID: 1002, Title: 'banana', sy: '香蕉' }], [{ GeneralID: 1003, Title: 'cherry', sy: '樱桃' }]];
- localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_word_orilist', JSON.stringify(pages));
- localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_total_page', '0');
- localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_current_learn', '1');
- const harness = await RouterTestingHarness.create();
- const router = TestBed.inject(Router);
- await harness.navigateByUrl('/pages/stu/pl_stu5?nids=811&pnid=801&orderId=901');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- const component = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- expect(component.words().length).toBe(2);
- component.skipSpellingStage();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/stu_con');
- const next = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- expect(next.words()[0].word).toBe('cherry');
- expect((TestBed.inject(ApiService) as unknown as LearningModulesApiService).studyUpdates.length).toBe(0);
- (harness.routeNativeElement?.querySelector('.app-header button[aria-label="返回"]') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toBe('/pages/shop/get_order?id=901');
- for (const key of ['_page_word_orilist', '_page_total_page', '_page_current_learn', 'skip_spelling_stage']) localStorage.removeItem(`xiaoshu.learning.300.100.901.unbound.${key}`);
- });
- it('keeps teacher-led spelling skipped through the remaining word groups', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- session.student.set({ userId: 100, honeyName: '张雅茜', groupId: 1 });
- const prefix = 'xiaoshu.learning.300.100.901.unbound.';
- const pages = [[{ GeneralID: 1001, Title: 'apple', sy: '苹果' }], [{ GeneralID: 1002, Title: 'banana', sy: '香蕉' }]];
- localStorage.setItem(prefix + '_page_word_orilist', JSON.stringify(pages));
- localStorage.setItem(prefix + '_page_current_learn', '1');
- const harness = await RouterTestingHarness.create();
- const router = TestBed.inject(Router);
- await harness.navigateByUrl('/pages/stu/pl_stu5?nids=811&pnid=801&orderId=901');
- const learning = () => harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- learning().skipSpellingStage();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/stu_con');
- expect(localStorage.getItem(prefix + 'skip_spelling_stage')).toBe('true');
- learning().skipStudyList();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- learning().chooseMatch('left', learning().words()[0]);
- learning().chooseMatch('right', learning().words()[0]);
- learning().continueAfterStage();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(router.url).toContain('/pages/stu/stu4');
- learning().chooseMeaning(learning().words()[0]);
- expect(learning().stageActionLabel).toBe('查看学习结果');
- learning().continueAfterStage();
- await harness.fixture.whenStable();
- expect(router.url).toContain('/pages/stu/pl_end');
- expect(localStorage.getItem(prefix + 'skip_spelling_stage')).toBe('true');
- localStorage.removeItem(prefix + 'skip_spelling_stage');
- }, 15000);
- it('resolves the appointment student before reading end results and offers an exit on failure', async () => {
- user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
- session.groupId.set(3);
- session.student.set({ userId: 999, honeyName: '之前的学员', groupId: 1 });
- const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
- const get = api.get.bind(api);
- spyOn(api, 'get').and.callFake((action, params) => action === 'app_lesson_study'
- ? throwError(() => new Error('学习记录暂时无法加载')) : get(action, params));
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/stu/pl_end?id=901');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- harness.fixture.detectChanges();
- expect(session.student()?.userId).toBe(100);
- expect(api.get).toHaveBeenCalledWith('app_lesson_study', {orderId:'901'});
- expect(harness.routeNativeElement?.querySelector('.empty-state.error')?.textContent).toContain('学习记录暂时无法加载');
- (harness.routeNativeElement?.querySelector('.empty-state.error .primary-button') as HTMLButtonElement).click();
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(TestBed.inject(Router).url).toBe('/pages/shop/get_order?id=901');
- });
- it('shows learning history in pages of twenty records', async () => {
- user.set({ userId: 777, userName: 'paged-student', honeyName: '分页学员', groupId: 1 });
- session.groupId.set(1);
- const harness = await RouterTestingHarness.create();
- await harness.navigateByUrl('/pages/his/his');
- await harness.fixture.whenStable();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.record-actions')?.textContent).toContain('45 条');
- expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(20);
- expect(harness.routeNativeElement?.querySelector('.record-pagination')?.textContent).toContain('第 1 / 3 页');
- const pageButtons = harness.routeNativeElement?.querySelectorAll('.record-pagination button') as NodeListOf<HTMLButtonElement>;
- expect(pageButtons[0].disabled).toBeTrue();
- pageButtons[1].click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(20);
- expect(harness.routeNativeElement?.querySelector('.record-pagination')?.textContent).toContain('第 2 / 3 页');
- (harness.routeNativeElement?.querySelectorAll('.record-pagination button')[1] as HTMLButtonElement).click();
- harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(5);
- expect((harness.routeNativeElement?.querySelectorAll('.record-pagination button')[1] as HTMLButtonElement).disabled).toBeTrue();
- });
- it('waits for server completion, blocks duplicate clicks and shows zero for overdue work', async()=>{
- user.set({userId:300,groupId:3,honeyName:'老师'});session.groupId.set(3);session.student.set({userId:100,groupId:1});
- const api=TestBed.inject(ApiService),post=api.post.bind(api),reply=new Subject<ApiEnvelope<any>>();
- const submit=spyOn(api,'post').and.callFake((action,params)=>action==='app_review_complete'?reply:post(action,params));
- const harness=await RouterTestingHarness.create();await harness.navigateByUrl('/pages/stu/record?id=900&gid=103&plannedDate=2000-01-01');await harness.fixture.whenStable();
- const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
- component.endRecord();component.endRecord();harness.fixture.detectChanges();expect(component.reviewCompletion()).toBeNull();expect(component.canDeactivate()).toBeFalse();
- expect(submit.calls.allArgs().filter(a=>a[0]==='app_review_complete').length).toBe(1);
- reply.next({retcode:1,result:{amount:0,rewardStatus:'ineligible',completed:true}});reply.complete();harness.fixture.detectChanges();
- expect(harness.routeNativeElement?.querySelector('.review-complete')?.textContent).toContain('本次收入 ¥0.00');expect(component.canDeactivate()).toBeTrue();
- });
- });
|