我猜测问题来自于使用共享的store
最终问题。我建议为每个测试单独存储。这个想法如下所示:
/** mock-store */
const createMockStore = configureMockStore([thunk]);
// Create a store maker to create store for each test
const storeMaker = () => {
const defaultState = [];
const store = createMockStore(defaultState);
return store;
}
/** reset mock */
afterEach(() => jest.resetAllMocks());
test("should register a user ", async () => {
// Run to create at each test
const store = storeMaker();
axios.mockImplementation(() => {
return Promise.resolve({
status: 200,
data: {
token: "testToken",
},
});
});
// const res = await axios.post("/api/users");
// console.log(res.body);
const testUser = {
name: "testName",
email: "test@email.com",
password: "testPassword",
};
await store.dispatch(register(testUser)).then(() => {
expect(store.getActions()[0]).toEqual({
type: REGISTER_SUCCESS,
payload: {
token: "testToken",
isAuthenticated: true,
loading: false,
},
});
});
});
test("should not register a user", async () => {
// Likewise above
const store = storeMaker();
axios.mockRejectedValue({
status: 500,
});
const userInfo = {
name: "",
email: "",
password: "",
};
await store.dispatch(register(userInfo)).then(() => {
expect(store.getActions()[0]).toEqual({
type: REGISTER_FAIL,
payload: {
token: null,
isAuthenticated: false,
loading: true,
// user: null,
},
});
});
});