我有一个使用“通用cookie”的React组件。在测试用例中调用mount时,cookie对象为空。
import Cookies from 'universal-cookie';
const cookies = new Cookies();
class MyComponent extends React.Component {
componentDidMount(){
axios.defaults.headers.common.Authorization = cookies.get('token').value; //12492525
}
}
//My Test File
describe('MyComponent Test', () => {
it('Component mounted', () => {
const wrapper = mount(<MyComponent/>);
});
});
运行测试文件时,我不断收到错误消息
“ TypeError:无法读取未定义的属性'value'的值”。
无论我尝试模拟或设置多少次,Cookies值都是空的。
到目前为止,我尝试设置
cookies.set('HAS_DOCUMENT_COOKIE', true);
cookies.set('token', { value: '1244'});// in my test file
答案 0 :(得分:1)
您可以使用jest.mock(moduleName, factory, options)个模拟universal-cookie
和axios
模块
例如
index.tsx
:
import React from "react";
import Cookies from "universal-cookie";
import axios from "axios";
const cookies = new Cookies();
export class MyComponent extends React.Component {
componentDidMount() {
axios.defaults.headers.common.Authorization = cookies.get("token").value; //12492525
console.log(axios.defaults.headers.common.Authorization);
}
render() {
return null;
}
}
index.spec.tsx
:
import React from "react";
import { shallow } from "enzyme";
import Cookies from "universal-cookie";
import axios from "axios";
import { MyComponent } from "./";
jest.mock("axios", () => {
return {
defaults: {
headers: {
common: {
Authorization: ""
}
}
}
};
});
jest.mock("universal-cookie", () => {
const mCookie = {
get: jest.fn()
};
return jest.fn(() => mCookie);
});
describe("MyComponent", () => {
afterEach(() => {
jest.resetAllMocks();
});
it("should set token correctly", () => {
const cookies = new Cookies();
(cookies.get as jest.Mocked<any>).mockReturnValueOnce({
value: "12492525"
});
const logSpy = jest.spyOn(console, "log");
const wrapper = shallow(<MyComponent></MyComponent>);
expect(axios.defaults.headers.common.Authorization).toBe("12492525");
expect(logSpy).toBeCalledWith("12492525");
});
});
覆盖率100%的单元测试结果:
PASS src/stackoverflow/59146770/index.spec.tsx (9.453s)
MyComponent
✓ should set token correctly (21ms)
console.log node_modules/jest-mock/build/index.js:860
12492525
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.887s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59146770