0👍
Due to jsdom#unimplemented-parts-of-the-web-platform, and we know from this issue: window.location.href can’t be changed in tests.
We need make a little change for the code, here is the solution:
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 p**n = new PornClass(studentId);
(StudentServices.getCollegeurl as jest.MockedFunction<
typeof StudentServices.getCollegeurl
>).mockResolvedValueOnce({ data: { collegeurl } });
await p**n.mounted();
expect(StudentServices.getCollegeurl).toBeCalledWith(studentId);
expect(window.location.href).toBe(collegeurl);
});
});
});
Unit test result with coverage report:
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
Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56482707
- [Vuejs]-Is there a way to ignore whitespace inside of the value of a <option> tag?
- [Vuejs]-The prop object's property is undefined in refresh function
Source:stackexchange.com