как проверить window.location.href в шутливых тестах

У меня есть метод в vue, который выполняет вызов службы и возвращает URL-адрес, а затем перенаправляет на него. это почти так выглядит

mounted () {
  StudentServices.getCollegeurl(this.studentId)
    .then(response => {
      window.location.href = response.data.collegeurl
    })
    .catch(response => {
      this.errorMessage = 'errr'
    })
}

Я издевался над StudentServices, и я могу подделать URL-адреса ... но в шутливых тестах я хочу убедиться, что window.location.href получает все, что я получаю от вызова службы ... Как я могу это сделать?


person Janier    schedule 06.06.2019    source источник


Ответы (1)


Из-за jsdom#unimplemented-parts-of-the-web- платформу, и из этой проблемы мы знаем: window.location.href не может быть изменено в тестах.

Нам нужно внести небольшое изменение в код, вот решение:

index.ts:

import { StudentServices } from './StudentServices';

export class PornClass {
  private errorMessage: string = '';
  constructor(private studentId: string) {}

  public async mounted() {
    return StudentServices.getCollegeurl(this.studentId)
      .then(response => {
        // window.location.href = response.data.collegeurl;
        Object.defineProperty(window, 'location', {
          value: {
            href: response.data.collegeurl
          }
        });
      })
      .catch(response => {
        this.errorMessage = 'errr';
      });
  }
}

StudentServices.ts:

export class StudentServices {
  public static async getCollegeurl(id: string) {
    return {
      data: {
        collegeurl: 'real url'
      }
    };
  }
}

index.spec.ts:

import { PornClass } from './';
import { StudentServices } from './StudentServices';

jest.mock('./StudentServices.ts', () => {
  const mockedStudentServices = {
    getCollegeurl: jest.fn()
  };
  return {
    StudentServices: mockedStudentServices
  };
});

describe('PornClass', () => {
  describe('#mounted', () => {
    it('should get college url and redirect correctly', async () => {
      const studentId = '1';
      const collegeurl = 'http://github.com/mrdulin';
      const porn = new PornClass(studentId);
      (StudentServices.getCollegeurl as jest.MockedFunction<
        typeof StudentServices.getCollegeurl
      >).mockResolvedValueOnce({ data: { collegeurl } });

      await porn.mounted();
      expect(StudentServices.getCollegeurl).toBeCalledWith(studentId);
      expect(window.location.href).toBe(collegeurl);
    });
  });
});

Результат модульного теста с отчетом о покрытии:

 PASS  src/stackoverflow/56482707/index.spec.ts
  PornClass
    #mounted
      ✓ should get college url and redirect correctly (8ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |       90 |      100 |       80 |    88.89 |                   |
 index.ts |       90 |      100 |       80 |    88.89 |                18 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.815s

Вот завершенная демонстрация: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56482707

person slideshowp2    schedule 26.09.2019